Skip to content
Velloreth
Web Development 4 min read

GraphQL Basics: Schema, Queries and Resolvers

GraphQL lets the client ask for exactly what it needs. Learn the schema, the query, the resolver, and the N+1 problem in practice.

By

The schema

type Post {
  id: ID!
  title: String!
  body: String!
  author: User!
  comments: [Comment!]!
}

type User {
  id: ID!
  name: String!
  posts: [Post!]!
}

type Query {
  post(id: ID!): Post
  posts(limit: Int = 10): [Post!]!
}

The schema defines the types and the fields.

! means non-null.

[Comment!]! is a non-null list of non-null comments.

The query

query {
  post(id: "1") {
    title
    author {
      name
    }
    comments {
      body
    }
  }
}

The client asks for the fields it needs, and the server returns exactly those.

No over-fetching, and no under-fetching.

The resolver

const resolvers = {
  Query: {
    post: (_, { id }, ctx) => ctx.db.post.findById(id),
  },
  Post: {
    author: (post, _, ctx) => ctx.db.user.findById(post.authorId),
    comments: (post, _, ctx) => ctx.db.comment.findByPostId(post.id),
  },
};

A resolver returns the data for one field.

It receives the parent value, the arguments and the context.

It can return a promise, and the runtime awaits it.

The N+1 problem

A query for 10 posts triggers 10 author queries and 10 comment queries.

1 query for the posts
10 queries for the authors
10 queries for the comments
= 21 queries

The fix: a batching loader.

const authorLoader = new DataLoader(async (ids) => {
  const users = await db.user.findByIds(ids);
  return ids.map((id) => users.find((u) => u.id === id));
});

The loader collects the keys in a tick and issues one query.

The result: 3 queries instead of 21.

The operations

OperationPurpose
Queryread
Mutationwrite
Subscriptiona real-time stream

A mutation is executed serially, so two mutations do not run in parallel.

A subscription uses a WebSocket and pushes an event.

The variables

query GetPost($id: ID!) {
  post(id: $id) {
    title
  }
}
{ "id": "1" }

A variable is passed separately, which avoids a string interpolation and enables a cache.

The fragments

fragment PostFields on Post {
  id
  title
}

query {
  posts {
    ...PostFields
  }
}

A fragment is a reusable field set.

A fragment on an interface is used with an inline fragment.

The security

Limit the query depth.

depthLimit(10)

Limit the query cost. Assign a cost per field and reject a query over a budget.

Disable introspection in production.

Require authentication, and authorise per field.

Rate limit by the cost, not by the request count.

A deeply nested query can be a denial of service, so the limits are not optional.

GraphQL versus REST

GraphQLREST
Endpointonemany
Over-fetchingnopossible
Under-fetchingnopossible
HTTP cachinghardeasy
Schemarequiredoptional
Complexityhigherlower
Best fora varied clienta fixed resource

GraphQL is better for a varied client, such as a web and a mobile app with different needs.

REST is simpler for a fixed resource, and it benefits from HTTP caching.

Common mistakes

No depth limit. A denial of service.

No cost limit. A heavy query.

Introspection in production. The schema is exposed.

The N+1 problem. A slow query.

No authorisation per field. A data leak.

A resolver that returns a promise without awaiting. A wrong value.

A mutation that is not idempotent. A retry duplicates.

No error handling. A partial result is not communicated.

A schema that changes without a version. A breaking change.

A cache that ignores the query. A wrong result.

A quotable summary

A GraphQL schema defines the types and the fields, the client asks for exactly the fields it needs, and a resolver fetches the data for one field. The N+1 problem is the main performance trap, and a batching loader such as DataLoader fixes it by collecting the keys and issuing one query. Limit the query depth and cost, disable introspection in production, and authorise per field, because a deeply nested query can be a denial of service.

For the related topics, see rest-api-design-principles and api-error-responses-guide. For the broader context, rest-api-rate-limiting and api-authentication-methods.

Frequently asked questions

What is GraphQL?
It is a query language and a runtime for an API, where the client sends a query that names the fields it needs and the server returns exactly those fields. The schema defines the types, and a resolver fetches the data for each field. It is an alternative to REST, not a replacement for it.
What is a resolver?
A function that returns the data for one field in the schema. A query field has a resolver, and each nested field has one too. The resolver receives the parent value, the arguments and the context, and it returns the value or a promise.
What is the N+1 problem?
It is when a query for a list of N items triggers one additional query per item, so N+1 queries run instead of two. It happens when a nested resolver fetches a related record one at a time. The fix is a batching loader, such as DataLoader, which collects the keys and issues one query.
What is the difference between GraphQL and REST?
REST exposes resources at URLs, and the client may need several requests to assemble a view. GraphQL exposes one endpoint and the client asks for the fields it needs in one request. GraphQL is better for a varied client, and REST is simpler for a fixed resource and benefits from HTTP caching.
How do I secure a GraphQL API?
Limit the query depth, limit the query cost, disable introspection in production, require authentication, and rate limit by the cost rather than by the request count. A deeply nested query can be a denial of service, so the limits are not optional.
What is a mutation?
A write operation. A query reads and a mutation writes. A mutation is executed serially, so two mutations do not run in parallel, which is what makes a write predictable. A subscription is a third operation, for a real-time stream.