GraphQL Fundamentals and Best Practices
A from-scratch tour of GraphQL: how a schema and resolvers replace a fixed set of REST endpoints, why queries always return 200 with errors in the body, query variables, the N+1 problem, and how GraphQL actually compares to REST.
The problem GraphQL exists to solve
A REST endpoint returns a fixed shape: GET /users/42 always returns the same set of fields, whether the client needs all of them or just the user's name. Two common pains follow from this. Overfetching is getting fields you don't need (a mobile screen that only shows a name and avatar still downloads the user's full address and preferences). Underfetching is the opposite: not getting enough in one call, forcing the client to make several follow-up requests (get the user, then get their posts, then get each post's comments) just to render one screen.
GraphQL's answer is to let the client describe exactly the shape of data it wants, in the request itself, and have the server return exactly that shape, no more and no less, from a single endpoint (conventionally POST /graphql) instead of one URL per resource.
query {
user(id: "42") {
name
posts {
title
comments {
text
}
}
}
}Note
One request, arbitrarily nested
The schema: a contract, not a suggestion
Every GraphQL API is described by a schema: a strongly-typed definition of every type, field, query, and mutation the API supports, written in GraphQL's own Schema Definition Language (SDL). The schema is the API's contract. A client can ask the server for its own schema (a feature called introspection) and use it to validate queries, autocomplete field names, and generate documentation, all without a human writing separate API docs by hand.
type Book {
id: ID!
title: String!
author: String
publishedYear: Int
}
type Query {
books: [Book!]!
book(id: ID!): Book
}- ! means non-null: Book! guarantees a Book is always returned, never null. [Book!]! means a non-null list of non-null Books (an empty list is fine; a list containing null is not).
- A scalar without ! (like author: String) can legitimately be null.
- Query is a special root type: every field on it is one of the "entry points" a client can ask for. Mutation is the equivalent root type for writes.
Query versus Mutation
A Query reads data and must not have side effects, mirroring REST's GET. A Mutation is how GraphQL represents a write, mirroring REST's POST/PUT/PATCH/DELETE all at once, since GraphQL doesn't have separate HTTP-verb-like concepts for different kinds of writes. By convention, a mutation's name describes the action (createBook, updateUser, deleteArticle) rather than the resource alone.
mutation {
createBook(title: "Dune", author: "Frank Herbert") {
id
title
}
}Example
A mutation response should return the thing that changed
Query variables: never build a query by string concatenation
It's tempting to build a query by pasting a value straight into the string (query { book(id: "42") { title } }), but that's the same class of mistake as building a SQL query by string concatenation: it's fragile (special characters in the value can break the query's syntax) and it means the client can never reuse one static query text for different inputs. GraphQL's answer is variables: declare a typed variable in the query, and pass its actual value in a separate variables object.
# The query text never changes, no matter which id you're looking up:
query GetBook($id: ID!) {
book(id: $id) {
title
}
}
# Sent alongside it, as a separate JSON object:
{ "id": "42" }Warning
This is a specific, commonly-tested best practice
Resolvers: the functions that actually fetch the data
The schema only describes shape; a resolver is the function attached to each field that actually produces its value; a database lookup, a call to another service, or (for a field on a nested type) simply reading a property off the object its parent resolver already returned. GraphQL execution walks the query field by field, calling each field's resolver in turn, passing the parent field's already-resolved value down to its children.
The N+1 problem: a very common GraphQL interview question
A naive resolver for "each book's author" looks innocent in isolation: given a book, fetch its author by id. The trap appears when a query asks for a list of 50 books and each one's author: that naive resolver runs once per book, firing 50 separate author-lookup queries (plus the 1 query that fetched the books themselves), for 51 total database round trips where 2 should have sufficed.
Warning
This is called the N+1 problem
The standard fix is a DataLoader (or an equivalent batching/caching layer): instead of each author resolver firing its own query immediately, it registers "I need author 7" into a shared batch, and at the end of the current tick, one single query fetches every distinct author id that was requested during this GraphQL execution, then hands each result back to the resolver that asked for it. The N+1 queries collapse into 2.
Why GraphQL always returns HTTP 200 (with errors in the body)
This surprises almost everyone coming from REST. A GraphQL HTTP response is, by convention, always 200 OK, even when part or all of the requested data failed to resolve. Errors are instead reported inside the response body itself, in a top-level errors array alongside (or instead of) the data field.
{
"data": { "book": null },
"errors": [
{
"message": "no resource at this id",
"extensions": { "code": "NOT_FOUND" }
}
]
}Note
Why not just use the HTTP status code like REST does?
The errors array doesn't have a single official vocabulary the way HTTP status codes do, but a widely-adopted convention (popularized by Apollo Server) is an extensions.code field on each error, using string codes like UNAUTHENTICATED, FORBIDDEN, BAD_USER_INPUT, or NOT_FOUND, playing the same role REST's status codes play, just carried in the body instead of the transport layer.
REST versus GraphQL: picking the right tool
REST | GraphQL | |
|---|---|---|
Endpoints | many, one (or a few) per resource | one, typically POST /graphql |
Response shape | fixed per endpoint | client-specified per request |
Over/underfetching | a real, common problem | designed to avoid both |
HTTP status codes | carry real meaning (401, 404, 422, ...) | always 200; errors live in the response body |
Caching | HTTP caching (ETags, Cache-Control) works out of the box | needs a GraphQL-aware client cache; HTTP caching barely applies since every request hits the same URL |
Tooling | OpenAPI/Swagger docs, generated separately | introspection generates docs/types from the schema itself |
Learning curve | lower; most developers already know HTTP verbs/status codes | higher; a new query language, resolver model, and error convention to learn |
Example
The honest interview answer is "it depends"
Practice these ideas hands-on
QuickRecall's GraphQL Playground (in the Node.js section of the sidebar) runs real queries and mutations, via the actual graphql-js reference implementation, against an in-browser schema covering zodiac signs/states/articles plus a custom resource you define yourself. Try a malformed query to see a real syntax error, remove the demo token to see an UNAUTHENTICATED error appear in the body while the status stays 200, and use its custom-resource tab to see genuine 422-equivalent BAD_USER_INPUT and 409-equivalent CONFLICT errors coming from real validation, not canned responses.