APIs · Intermediate · 26 min
Build your first GraphQL API with Apollo Server
By Padding · Updated 18 Nov 2026
Node.js 26.13 (node:26 image) · @apollo/server 5.5.2 · graphql 16.15.0 · dataloader 2.2.3 · graphql-depth-limit 1.1.0
You will have a GraphQL API for authors and books on Apollo Server 5.5 and Node.js 26, with a mutation that rejects bad input, batched database calls through DataLoader, a query depth limit, and a clear idea of what it costs to run.
On this page
GraphQL puts one endpoint in front of your data and lets the client say exactly which fields it wants. The server publishes a schema, a typed description of everything that can be asked for, and runs a small function, a resolver, for each field in the request. That flexibility is the attraction, and it is also where the costs come from: a client can ask for a lot in one request, and a careless resolver can turn one request into dozens of database calls.
You will build an API for authors and books with Apollo Server, a widely used GraphQL server for Node.js. You will query it with curl and from a small fetch client, add a book through a mutation that rejects bad input, watch the N+1 problem happen in your server log, fix it with DataLoader, and refuse queries that nest too deeply. The data lives in memory behind a module that prints every "SQL" statement it would run, so you can count database calls without installing a database.
One version note before you start. The graphql package is at 17, but Apollo Server 5 declares a peer dependency on graphql 16 (^16.11.0). Install graphql@16. If you install 17, npm reports an ERESOLVE peer dependency conflict, and Apollo Server is not tested against it.
Step 1 · Create the project
Make a folder, turn on ES modules, and install Apollo Server with graphql 16. The exact versions keep your results the same as this page:
mkdir -p ~/books-graphql
cd ~/books-graphql
npm init -y
npm pkg set type=module
npm install @apollo/server@5.5.2 graphql@16.15.0Check it worked
npm ls @apollo/server graphqlThe tree lists @apollo/server@5.5.2 and graphql@16.15.0, with no UNMET PEER DEPENDENCY or invalid markers.
Step 2 · Write a data module that logs every query
In a real app the resolvers would call PostgreSQL or another database. Here data.js holds three authors and six books in arrays and prints the statement it would send, so the server log shows each round trip. Each function waits 5 milliseconds, like a fast database on the same network. The author names include Ngũgĩ wa Thiong’o, whose name carries tilde and apostrophe characters that must survive the round trip as UTF-8; names in Yoruba, Igbo, Kikuyu and many other languages need the same care.
cat > data.js <<'JS'
const authors = [
{ id: '1', name: 'Chinua Achebe' },
{ id: '2', name: 'Ngũgĩ wa Thiong’o' },
{ id: '3', name: 'Chimamanda Ngozi Adichie' },
]
const books = [
{ id: '1', title: 'Things Fall Apart', year: 1958, authorId: '1' },
{ id: '2', title: 'Arrow of God', year: 1964, authorId: '1' },
{ id: '3', title: 'A Grain of Wheat', year: 1967, authorId: '2' },
{ id: '4', title: 'Petals of Blood', year: 1977, authorId: '2' },
{ id: '5', title: 'Half of a Yellow Sun', year: 2006, authorId: '3' },
{ id: '6', title: 'Americanah', year: 2013, authorId: '3' },
]
function query(sql) {
console.log(`db: ${sql}`)
return new Promise((resolve) => setTimeout(resolve, 5))
}
export async function listBooks() {
await query('SELECT * FROM books')
return books
}
export async function findBook(id) {
await query(`SELECT * FROM books WHERE id = ${id}`)
return books.find((book) => book.id === id) ?? null
}
export async function listAuthors() {
await query('SELECT * FROM authors')
return authors
}
export async function findAuthor(id) {
await query(`SELECT * FROM authors WHERE id = ${id}`)
return authors.find((author) => author.id === id) ?? null
}
export async function findAuthors(ids) {
await query(`SELECT * FROM authors WHERE id IN (${ids.join(', ')})`)
return ids.map((id) => authors.find((author) => author.id === id) ?? null)
}
export async function booksByAuthor(authorId) {
await query(`SELECT * FROM books WHERE author_id = ${authorId}`)
return books.filter((book) => book.authorId === authorId)
}
export async function booksByAuthors(authorIds) {
await query(`SELECT * FROM books WHERE author_id IN (${authorIds.join(', ')})`)
return books.filter((book) => authorIds.includes(book.authorId))
}
export async function insertBook({ title, year, authorId }) {
await query('INSERT INTO books (title, year, author_id) VALUES (...)')
const book = { id: String(books.length + 1), title, year, authorId }
books.push(book)
return book
}
JSThe printed SQL is for reading only. It pastes values into strings, which you must never do with a real database: use your driver's parameters ($1, ?) instead. findAuthors and booksByAuthors fetch many rows in one call; you will need them in the DataLoader step.
Check it worked
node -e "import('./data.js').then(async (db) => console.log((await db.findAuthor('2')).name))"The output is two lines: db: SELECT * FROM authors WHERE id = 2, then Ngũgĩ wa Thiong’o with its accents intact. If the name shows as NgÅ©gÄ© or similar, your terminal is not set to UTF-8.
Step 3 · Define the schema and start the server
The schema is the contract. Create schema.js:
cat > schema.js <<'JS'
export const typeDefs = `#graphql
type Author {
id: ID!
name: String!
books: [Book!]!
}
type Book {
id: ID!
title: String!
year: Int!
author: Author!
}
input AddBookInput {
title: String!
year: Int!
authorId: ID!
}
type Query {
books: [Book!]!
book(id: ID!): Book
authors: [Author!]!
author(id: ID!): Author
}
type Mutation {
addBook(input: AddBookInput!): Book!
}
`
JS! means a value is never null. [Book!]! is a list that is always present and never holds a null. Book and Author point at each other, so a client can walk from a book to its author and back. AddBookInput is an input type: a named bundle of arguments, which keeps the mutation signature short and lets you add optional fields later without breaking clients. book(id:) and author(id:) return a nullable type, so an unknown id gives null rather than an error.
Now resolvers.js. Each key mirrors a type in the schema, and each function returns the value for that field, or a promise of it:
cat > resolvers.js <<'JS'
import { GraphQLError } from 'graphql'
import * as db from './data.js'
function badInput(message, field) {
return new GraphQLError(message, {
extensions: { code: 'BAD_USER_INPUT', field },
})
}
export const resolvers = {
Query: {
books: () => db.listBooks(),
book: (_parent, { id }) => db.findBook(id),
authors: () => db.listAuthors(),
author: (_parent, { id }) => db.findAuthor(id),
},
Mutation: {
addBook: async (_parent, { input }) => {
const title = input.title.trim()
if (title.length < 1 || title.length > 200) {
throw badInput('Title must be 1 to 200 characters', 'title')
}
const thisYear = new Date().getFullYear()
if (input.year < 1000 || input.year > thisYear) {
throw badInput(`Year must be between 1000 and ${thisYear}`, 'year')
}
if (!(await db.findAuthor(input.authorId))) {
throw badInput(`No author with id ${input.authorId}`, 'authorId')
}
return db.insertBook({ ...input, title })
},
},
Book: {
author: (book) => db.findAuthor(book.authorId),
},
Author: {
books: (author) => db.booksByAuthor(author.id),
},
}
JSA resolver receives the parent object first. Book.author gets the book that Query.books returned and looks up its author; fields such as title need no resolver because GraphQL reads book.title by default.
Finally index.js, which builds the server and starts it:
cat > index.js <<'JS'
import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'
import { typeDefs } from './schema.js'
import { resolvers } from './resolvers.js'
const server = new ApolloServer({
typeDefs,
resolvers,
includeStacktraceInErrorResponses: false,
formatError(formattedError, error) {
if (formattedError.extensions?.code === 'INTERNAL_SERVER_ERROR') {
console.error(error)
return { message: 'Internal server error', extensions: { code: 'INTERNAL_SERVER_ERROR' } }
}
return formattedError
},
})
const port = Number(process.env.PORT ?? 4000)
const { url } = await startStandaloneServer(server, {
listen: { port, host: '127.0.0.1' },
})
console.log(`Ready at ${url}`)
JSincludeStacktraceInErrorResponses: false keeps stack traces out of responses; Apollo Server adds them by default unless NODE_ENV is production. formatError replaces the message of any unexpected error (a bug, a dropped database connection) with a fixed one, and prints the real error where only you can see it. Errors you throw on purpose, with a code such as BAD_USER_INPUT, pass through unchanged.
Start the server in a second terminal. --watch restarts it whenever you save a file:
cd ~/books-graphql
node --watch index.jsCheck it worked
The terminal shows something like Ready at http://127.0.0.1:4000/. Ask for one field:
curl -s --json '{"query":"{ __typename }"}' http://127.0.0.1:4000/The output is {"data":{"__typename":"Query"}}. If you open the address in a browser, Apollo Server shows a landing page that loads Apollo Sandbox, an in-browser query editor, from Apollo's CDN.
Step 4 · Send queries with curl and from a fetch client
A GraphQL request is an HTTP POST with a JSON body holding query and, optionally, variables. --json sets the Content-Type: application/json header, which Apollo Server requires as part of its protection against cross-site request forgery:
curl -s --json '{"query":"{ books { title year } }"}' http://127.0.0.1:4000/The response lists the six books with only their titles and years: {"data":{"books":[{"title":"Things Fall Apart","year":1958},.... Ask for different fields and the shape of the response follows. Pass arguments as variables rather than pasting them into the query text, so the query stays the same string for every caller:
curl -s --json '{"query":"query Book($id: ID!) { book(id: $id) { title author { name } } }","variables":{"id":"5"}}' http://127.0.0.1:4000/The output is {"data":{"book":{"title":"Half of a Yellow Sun","author":{"name":"Chimamanda Ngozi Adichie"}}}}.
A browser or Node app does the same with fetch. Create client.js, which prints one author's books:
cat > client.js <<'JS'
const endpoint = process.env.GRAPHQL_URL ?? 'http://127.0.0.1:4000/'
const query = `
query AuthorBooks($id: ID!) {
author(id: $id) {
name
books { title year }
}
}
`
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ query, variables: { id: process.argv[2] ?? '1' } }),
})
const { data, errors } = await response.json()
if (errors) {
for (const error of errors) console.error(`${error.extensions?.code}: ${error.message}`)
process.exitCode = 1
} else if (!data.author) {
console.log(`No author with id ${process.argv[2]}`)
} else {
console.log(data.author.name)
for (const book of data.author.books) console.log(` ${book.year} ${book.title}`)
}
JS
node client.js 1Check errors before data: a GraphQL response can carry both, and an error is not always signalled by the HTTP status.
Check it worked
The output is:
Chinua Achebe
1958 Things Fall Apart
1964 Arrow of GodRun node client.js 9 and it prints No author with id 9, because author(id:) is nullable.
Step 5 · Add a book and handle errors
Send the mutation with its input as a variable:
curl -s --json '{"query":"mutation Add($input: AddBookInput!) { addBook(input: $input) { id title author { name } } }","variables":{"input":{"title":" Wizard of the Crow ","year":2006,"authorId":"2"}}}' http://127.0.0.1:4000/The response holds the new book with id 7 and the title trimmed to Wizard of the Crow. Now try four kinds of mistake. -w adds the HTTP status on its own line:
curl -s -w '%{http_code}\n' --json '{"query":"mutation Add($input: AddBookInput!) { addBook(input: $input) { id } }","variables":{"input":{"title":"Matigari","year":1986,"authorId":"99"}}}' http://127.0.0.1:4000/
curl -s -w '%{http_code}\n' --json '{"query":"mutation Add($input: AddBookInput!) { addBook(input: $input) { id } }","variables":{"input":{"title":"Matigari","year":"1986","authorId":"2"}}}' http://127.0.0.1:4000/
curl -s -w '%{http_code}\n' --json '{"query":"{ books { titel } }"}' http://127.0.0.1:4000/
curl -s -w '%{http_code}\n' --json '{"query":"{ books { title }"}' http://127.0.0.1:4000/They fail at different stages, and Apollo Server reports each one differently:
- An unknown author id passes the schema, so your resolver runs and throws. The response is
200with"data":nulland an error whoseextensionshold"code":"BAD_USER_INPUT"and"field":"authorId". The status is200because the request itself was valid GraphQL; the error is in the body. - A year sent as the string
"1986"does not matchInt, so the request is rejected before any resolver runs:400, codeBAD_USER_INPUT, messageVariable "$input" got invalid value "1986" at "input.year"; Int cannot represent non-integer value: "1986". - Asking for a field that does not exist is a validation error:
400, codeGRAPHQL_VALIDATION_FAILED, withDid you mean "title"?in the message. - A missing closing brace is a syntax error:
400, codeGRAPHQL_PARSE_FAILED.
None of them includes a stack trace. A client should read extensions.code, which is stable, rather than match on message text.
Check it worked
curl -s --json '{"query":"mutation Add($input: AddBookInput!) { addBook(input: $input) { id } }","variables":{"input":{"title":" ","year":1986,"authorId":"2"}}}' http://127.0.0.1:4000/The error message is Title must be 1 to 200 characters, because a title of spaces is empty once trimmed. The schema can say a field is a String; rules such as length and range belong in the resolver.
Step 6 · See the N+1 problem and fix it with DataLoader
Watch the server terminal and ask for every book with its author's name:
curl -s --json '{"query":"{ books { title author { name } } }"}' http://127.0.0.1:4000/The log shows one SELECT * FROM books, then one SELECT * FROM authors WHERE id = ... for each of the seven books: eight round trips for one request, with the same author fetched more than once. That is the N+1 problem. Book.author runs once per book and knows nothing about the others. With 100 books on a page it would be 101 queries.
DataLoader fixes it. During one tick of the event loop it collects every load(id) call, then calls your batch function once with all the ids. It also caches each id for the life of the loader. Create a new set of loaders for every request, so one user's cached rows never reach another user. Install it:
npm install dataloader@2.2.3Create loaders.js. A batch function must return results in the same order as the keys it was given, one per key:
cat > loaders.js <<'JS'
import DataLoader from 'dataloader'
import * as db from './data.js'
export function createLoaders() {
return {
author: new DataLoader((ids) => db.findAuthors(ids)),
booksByAuthor: new DataLoader(async (authorIds) => {
const rows = await db.booksByAuthors(authorIds)
return authorIds.map((id) => rows.filter((book) => book.authorId === id))
}),
}
}
JSRewrite resolvers.js so the two relationship fields read through the loaders, which they find in the context, the third argument every resolver receives:
cat > resolvers.js <<'JS'
import { GraphQLError } from 'graphql'
import * as db from './data.js'
function badInput(message, field) {
return new GraphQLError(message, {
extensions: { code: 'BAD_USER_INPUT', field },
})
}
export const resolvers = {
Query: {
books: () => db.listBooks(),
book: (_parent, { id }) => db.findBook(id),
authors: () => db.listAuthors(),
author: (_parent, { id }) => db.findAuthor(id),
},
Mutation: {
addBook: async (_parent, { input }) => {
const title = input.title.trim()
if (title.length < 1 || title.length > 200) {
throw badInput('Title must be 1 to 200 characters', 'title')
}
const thisYear = new Date().getFullYear()
if (input.year < 1000 || input.year > thisYear) {
throw badInput(`Year must be between 1000 and ${thisYear}`, 'year')
}
if (!(await db.findAuthor(input.authorId))) {
throw badInput(`No author with id ${input.authorId}`, 'authorId')
}
return db.insertBook({ ...input, title })
},
},
Book: {
author: (book, _args, { loaders }) => loaders.author.load(book.authorId),
},
Author: {
books: (author, _args, { loaders }) => loaders.booksByAuthor.load(author.id),
},
}
JSRewrite index.js to build that context. Apollo Server calls the context function once per request:
cat > index.js <<'JS'
import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'
import { typeDefs } from './schema.js'
import { resolvers } from './resolvers.js'
import { createLoaders } from './loaders.js'
const server = new ApolloServer({
typeDefs,
resolvers,
includeStacktraceInErrorResponses: false,
formatError(formattedError, error) {
if (formattedError.extensions?.code === 'INTERNAL_SERVER_ERROR') {
console.error(error)
return { message: 'Internal server error', extensions: { code: 'INTERNAL_SERVER_ERROR' } }
}
return formattedError
},
})
const port = Number(process.env.PORT ?? 4000)
const { url } = await startStandaloneServer(server, {
listen: { port, host: '127.0.0.1' },
context: async () => ({ loaders: createLoaders() }),
})
console.log(`Ready at ${url}`)
JS--watch restarts the server when the files change. The data lives in memory, so the restart takes it back to the six starting books.
Check it worked
Send the same query, plus one that walks from authors to books and back:
curl -s --json '{"query":"{ books { title author { name } } }"}' http://127.0.0.1:4000/
curl -s --json '{"query":"{ authors { name books { title author { name } } } }"}' http://127.0.0.1:4000/The first now logs two statements: SELECT * FROM books and SELECT * FROM authors WHERE id IN (1, 2, 3). The second logs three: authors, then books WHERE author_id IN (1, 2, 3), then the author batch. The number of queries now depends on how deep the request goes, not on how many rows come back.
Step 7 · Limit how deep a query can go
Because Author and Book point at each other, a client can nest them as deep as it likes. Each level multiplies the work by the length of the lists involved, and DataLoader's cache only helps when the same ids come back. A depth limit refuses such a query during validation, before any resolver runs. graphql-depth-limit does this in one small file; it has not changed since 2022, works with graphql 16, and is easy to read before you trust it.
npm install graphql-depth-limit@1.1.0Rewrite index.js once more, adding the rule to validationRules:
cat > index.js <<'JS'
import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'
import depthLimit from 'graphql-depth-limit'
import { typeDefs } from './schema.js'
import { resolvers } from './resolvers.js'
import { createLoaders } from './loaders.js'
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [depthLimit(5)],
includeStacktraceInErrorResponses: false,
formatError(formattedError, error) {
if (formattedError.extensions?.code === 'INTERNAL_SERVER_ERROR') {
console.error(error)
return { message: 'Internal server error', extensions: { code: 'INTERNAL_SERVER_ERROR' } }
}
return formattedError
},
})
const port = Number(process.env.PORT ?? 4000)
const { url } = await startStandaloneServer(server, {
listen: { port, host: '127.0.0.1' },
context: async () => ({ loaders: createLoaders() }),
})
console.log(`Ready at ${url}`)
JSPick the limit from your own schema: find the deepest query your real clients send and allow a little more. Five suits this one.
Check it worked
curl -s -w '%{http_code}\n' --json '{"query":"query Deep { authors { books { author { books { author { books { title } } } } } } }"}' http://127.0.0.1:4000/
curl -s -w '%{http_code}\n' --json '{"query":"{ authors { name books { title author { name } } } }"}' http://127.0.0.1:4000/The first answers 400 with 'Deep' exceeds maximum operation depth of 5 and code GRAPHQL_VALIDATION_FAILED, and the server log shows no db: line for it. The second, three levels deep, still answers 200 with data.
Step 8 · Understand what it costs to run
Compare what two clients pay for different questions to the same endpoint:
curl -s -o /dev/null -w '%{size_download} bytes\n' --json '{"query":"{ books { title } }"}' http://127.0.0.1:4000/
curl -s -o /dev/null -w '%{size_download} bytes\n' --json '{"query":"{ books { id title year author { id name books { id title year } } } }"}' http://127.0.0.1:4000/The first is a couple of hundred bytes; the second is several times larger for the same six books. On prepaid mobile data and low-end Android phones, which is how many people across Africa reach your app, a client that asks only for the fields on screen saves real money and parsing time. That saving is GraphQL's main selling point. The bill for it lands on the server:
- No free HTTP caching. Every request is a
POSTto one URL, so CDNs and browser caches do not store responses. To cache, send queries asGETand use automatic persisted queries, which replace the query text with a hash; see Apollo's APQ documentation. - Work per field, not per request. A request runs a resolver for every field of every object. Batch with DataLoader, as you did, and look at resolver timings in your tracing before you guess.
- Cost limits are your job. The depth limit is a start. Lists also need a maximum page size (a
first: Intargument capped in the resolver), and a public API may need a cost or complexity limit and rate limiting on top. See paginate API results with cursors and rate limit an API in application code. - The standalone server is for getting started.
startStandaloneServeraccepts JSON bodies up to 50 MB and answers CORS requests from any origin. For production, mount Apollo Server in Express 5 with@as-integrations/express5, set your own body limit and CORS origins, and run it behind a reverse proxy, as in build a REST API with Express 5. - Set
NODE_ENV=production. Apollo Server then turns off introspection, so strangers cannot download your full schema, and the landing page changes to a production one. Your own tools can still use the schema file.
Check it worked
The second number is at least three times the first. If both are the same size, check that you sent two different queries.
Step 9 · Stop the server and clean up
Press Ctrl+C in the server terminal. Apollo Server finishes requests in flight, then exits. Delete the project folder, which holds only what you made here:
cd ~
rm -rf ~/books-graphqlCheck it worked
curl -s --json '{"query":"{ __typename }"}' http://127.0.0.1:4000/ prints nothing and exits with an error (echo $? shows 7, could not connect), and ls ~/books-graphql reports that the folder does not exist.
Next steps
- Decide when GraphQL is the right tool and when it is not: choose between REST, GraphQL and gRPC.
- Build the same kind of service the REST way and compare the error handling: build a REST API with Express 5.
- Turn the curl requests from this page into a repeatable check: test an API with curl.
- Try a typed, binary alternative for service-to-service calls: build a gRPC service with Protocol Buffers.
Part of these paths
Related tutorials
- Choose between REST, GraphQL and gRPC for your APIYou will choose an API style for three real scenarios by weighing who calls each API, caching, browser support, payload size, streaming, tooling and team skills, and record each choice in a one-page decision record.
- Design REST endpoints: resources, methods and status codesYou will design the endpoints of an event ticketing API on one page, build an Express 5 stub that follows it, and prove every status code in the design with curl.
- How to Build a REST API with Express 5You will build a small items API with Express 5.3 on Node.js 26 that validates its input, returns the right HTTP status codes, never sends a stack trace to callers, and has automated tests that use only Node's built-in test runner.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials