GraphQL basics
GraphQL is a query language for APIs, created at Facebook and now used by GitHub, Shopify, Netflix and many others. Instead of many endpoints that each return a fixed shape, a GraphQL API has one endpoint and a typed schema, and the client asks for exactly the fields it needs.
The problem it solves
To show a book page with its author and the author's other books, a REST client might need:
GET /books/1 → { id, title, year, pages, isbn, authorId, … } more than needed
GET /authors/7 → { id, name, bio, born, … }
GET /authors/7/books → [ … ]Three round trips (under-fetching) and lots of unused fields (over-fetching). With GraphQL it's one request, shaped like the answer you want:
query {
book(id: "1") {
title
author {
name
books { title }
}
}
}{
"data": {
"book": {
"title": "A Wizard of Earthsea",
"author": { "name": "Ursula K. Le Guin", "books": [{ "title": "A Wizard of Earthsea" }, { "title": "The Dispossessed" }] }
}
}
}The schema
Everything starts with a schema written in the Schema Definition Language (SDL). It lists the types, their fields, and the entry points: Query for reading and Mutation for writing.
type Author {
id: ID!
name: String!
books: [Book!]!
}
type Book {
id: ID!
title: String!
year: Int
author: Author!
}
type Query {
books(limit: Int = 10): [Book!]!
book(id: ID!): Book
}
type Mutation {
addBook(title: String!, year: Int, authorId: ID!): Book!
}- Built-in scalars:
String,Int,Float,Boolean,ID. !means non-null:String!always has a value;Book(no!) may benull, e.g. when the id doesn't exist.[Book!]!is a non-null list of non-null books.
Resolvers
The schema says what can be asked; resolvers are the functions that fetch each field. Here's a complete GraphQL API using the official graphql package:
The same schema answered three very different questions, and each response contains exactly the fields requested.
Variables
Don't build queries by pasting values into strings. Declare variables with types, and send their values separately:
Because every query is checked against the schema, typos and wrong types are rejected before any resolver runs, with precise error messages.
Serving GraphQL over HTTP
A GraphQL API is usually a single POST /graphql endpoint that receives { query, variables } and returns { data, errors }:
In real projects, use a server library such as Apollo Server, GraphQL Yoga or Mercurius: they add a browser playground, file uploads, subscriptions and better error handling. GraphQL errors usually come back with status 200 and an errors array, so clients must check errors, not just the status code.
The N+1 problem
Asking for 50 books with their authors can make the author resolver run 50 separate database queries, plus one for the books: N+1 queries. The standard fix is DataLoader, which collects all the author IDs requested during one tick and loads them in a single batched query (WHERE id IN (…)):
import DataLoader from 'dataloader';
const authorLoader = new DataLoader(async (ids) => {
const rows = await db.query('SELECT * FROM authors WHERE id = ANY($1)', [ids]);
return ids.map((id) => rows.find((r) => r.id === id)); // same order as the ids
});
// in the Book type's resolver:
author: (book) => authorLoader.load(book.authorId),GraphQL or REST?
| REST | GraphQL | |
|---|---|---|
| Endpoints | Many, one per resource | One |
| Response shape | Fixed by the server | Chosen by the client |
| Typing | Optional (OpenAPI) | Built in (the schema) |
| HTTP caching | Easy (GET + URLs) | Harder (POST to one URL) |
| Errors | HTTP status codes | errors array, usually with 200 |
| Best for | Public APIs, simple CRUD, file downloads | Rich frontends needing data from many related types, mobile apps |
Many companies use both: REST for public and simple APIs, GraphQL as a flexible layer for their own frontends.
Security
Clients can write arbitrarily deep queries (author { books { author { books { … } } } }). Production GraphQL servers limit query depth and complexity, paginate lists, apply timeouts, and often disable schema introspection for public clients.
Practice
- Add an
authors: [Author!]!query and request every author's name with the titles of their books. - Add a
deleteBook(id: ID!): Boolean!mutation. - Write a query with a variable
$year: Int!that returns books published after that year (add abooksAfter(year: Int!)field).
1.What is "over-fetching"?
2.What does String! mean in a GraphQL schema?
3.Which technique solves the N+1 query problem in GraphQL resolvers?