Lesson 2: Building a GraphQL API from Scratch

 📌 Goal: By the end of this, you'll have a working GraphQL API with queries, mutations, and resolvers.


🛠️ Step 1: Setting Up a GraphQL Server

We’ll use Node.js with Apollo Server. If you haven't already, install dependencies:


mkdir graphql-server && cd graphql-server npm init -y npm install apollo-server graphql

Then, create a file index.js and set up a basic Apollo Server:


const { ApolloServer, gql } = require('apollo-server'); // Define schema const typeDefs = gql` type Book { id: ID! title: String! author: String! } type Query { books: [Book] } `; // Sample data const books = [ { id: "1", title: "The Pragmatic Programmer", author: "Andy Hunt" }, { id: "2", title: "Clean Code", author: "Robert C. Martin" } ]; // Define resolvers const resolvers = { Query: { books: () => books, }, }; // Start the server const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`🚀 Server ready at ${url}`); });

🔥 Step 2: Running Your GraphQL API

Run:


node index.js

You should see:


🚀 Server ready at http://localhost:4000/

Open http://localhost:4000/ in your browser, and run this query in Apollo Sandbox:


{ books { title author } }

🎉 Congrats! You just built a working GraphQL API.


🛠️ Step 3: Adding Mutations (Write Operations)

Now, let’s allow users to add books. Modify typeDefs:


type Mutation { addBook(title: String!, author: String!): Book }

Update resolvers:


Mutation: { addBook: (_, { title, author }) => { const newBook = { id: String(books.length + 1), title, author }; books.push(newBook); return newBook; } }

Restart your server, then test with this mutation:


mutation { addBook(title: "GraphQL in Action", author: "Sam Newman") { id title author } }

Now, re-run your books query and see the new book added! 🚀


🤔 Reflection & Next Steps

  • What did you learn from this?
  • How would you add update and delete mutations?
  • Want to connect this to a database (MongoDB/PostgreSQL)?
  • Want to integrate GraphQL with a frontend (React/Next.js)?

🤔 1. What did you learn from this lesson?

In the land of APIs, you became a conjurer of structure and clarity.

You learned how to:

  • Set up a basic GraphQL server using Apollo Server.
  • Define a schema with typeDefs — the contract of what your API offers.
  • Create resolvers — the logic behind each query or mutation.
  • Perform read (Query) and write (Mutation) operations.
  • Run your GraphQL server and interact with it via Apollo Sandbox.

In essence: You moved from concept to real code, bringing GraphQL from theory to reality.


🔄 2. How would you add update and delete mutations?

Let’s answer this with a quick code sketch, then unpack it logically.

Update Mutation:


type Mutation { updateBook(id: ID!, title: String, author: String): Book }

updateBook: (_, { id, title, author }) => { const book = books.find(b => b.id === id); if (!book) return null; if (title) book.title = title; if (author) book.author = author; return book; }

Delete Mutation:


type Mutation { deleteBook(id: ID!): Boolean }

deleteBook: (_, { id }) => { const index = books.findIndex(b => b.id === id); if (index === -1) return false; books.splice(index, 1); return true; }

Story behind the code: You are now crafting full CRUD spells. You can not only summon (read/create) data, but also reshape (update) or banish it (delete).


🧩 3. Do you want to connect this to a database?

This question’s a prompt for next direction, but here’s a quick reflection:

In-memory data (like our books array) is great for demos. But real applications need persistence.

By connecting to a real database, like:

  • MongoDB (NoSQL)
  • PostgreSQL (SQL)
  • Prisma or Mongoose as ORM/ODM

…you can store, retrieve, and manage data that lives beyond server restarts.

🔮 With a database, your GraphQL API gains memory and history — your spellbook becomes a grimoire.


⚛️ 4. Want to integrate GraphQL with the frontend (React/Next.js)?

You’ll unlock:

  • Apollo Client (cache + query manager)
  • React Hooks like useQuery and useMutation
  • Real-time updates with subscriptions

This is the next level of the adventure: taking your API and letting the frontend fetch, mutate, and render data — all declaratively.

Imagine a React app that speaks GraphQL fluently — asking only for what it needs and reacting instantly to changes.


🧠 Summary Answer Map:

QuestionAnswer Summary
What did you learn?How to build and run a GraphQL API with queries/mutations
How to update/delete?Add new mutation types + logic in resolvers
Why use a database?To persist and scale beyond in-memory structures
Next step with frontend?Use Apollo Client with React/Next.js for data-driven UIs

Comments

Popular posts from this blog

The Story Begins: A World Drowning in REST