← Back to Node.js, page 9

nodejs-0164 · Easy fresher

What is GraphQL, how do a schema, queries, variables and resolvers work, and how does it differ from REST?

GraphQL is a query language and runtime for APIs. A typed schema describes the data, the client sends a query that names exactly the fields it wants, and the server runs a resolver function for each field. One endpoint serves many shapes of data, which avoids over-fetching and extra round trips, but moves complexity to the server (caching, N+1 queries, query cost, security).

Full answer

Core ideas

  • Schema (SDL): types, fields, arguments, Query (reads), Mutation (writes) and Subscription (live updates). Types are non-null or nullable (String!).
  • Query: the client selects fields. { student(id: 1) { name marks } } returns only name and marks, in that shape.
  • Variables: pass values separately from the query text (query ($id: ID!) { ... }), which is safer and cacheable.
  • Resolvers: functions (parent, args, context, info) that return the value of a field. If a field has no resolver, GraphQL reads the property with the same name from the parent object.
  • Errors: a response can contain data and errors together (partial results). A nullable field that fails becomes null and adds an error entry.
  • Introspection: clients can ask the schema about itself, which powers tools and code generation.

Compared with REST

  • One endpoint (POST /graphql) versus many resources. The client controls the shape of the response.
  • Fewer round trips for nested data, and no versioning by URL (fields are added and deprecated).
  • Harder: HTTP caching (everything is a POST by default), N+1 resolver queries (see DataLoader), unbounded query cost and file uploads. Errors return HTTP 200 in many servers.
  • REST is simpler for plain CRUD and public caching. GraphQL helps when many different clients need different data.

In Node: graphql-js is the reference implementation. Apollo Server, GraphQL Yoga and Mercurius add HTTP, tooling and plugins.

javascript
const { buildSchema, graphql } = require('graphql');

const schema = buildSchema(`
  type Student { id: ID!  name: String!  marks: Int!  grade: String! }
  type Query {
    student(id: ID!): Student
    students(minMarks: Int = 0): [Student!]!
  }
  type Mutation { addStudent(name: String!, marks: Int!): Student! }
`);

const data = [{ id: '1', name: 'Asha', marks: 78 }, { id: '2', name: 'Ravi', marks: 64 }];
const withGrade = (s) => s && { ...s, grade: s.marks >= 75 ? 'A' : 'B' };          // a computed field
const rootValue = {
  student: ({ id }) => withGrade(data.find((s) => s.id === id)),
  students: ({ minMarks }) => data.filter((s) => s.marks >= minMarks).map(withGrade),
  addStudent: ({ name, marks }) => { const s = { id: String(data.length + 1), name, marks }; data.push(s); return withGrade(s); },
};

const run = async (label, source, variableValues) => {
  const result = await graphql({ schema, source, rootValue, variableValues });
  console.log(label.padEnd(26), JSON.stringify(result));
};

(async () => {
  await run('only name and grade', '{ student(id: "1") { name grade } }');
  await run('variables + alias', 'query ($min: Int) { top: students(minMarks: $min) { name } }', { min: 70 });
  await run('mutation', 'mutation { addStudent(name: "Meera", marks: 91) { id name grade } }');
  await run('unknown id (nullable)', '{ student(id: "99") { name } }');
  await run('unknown field', '{ student(id: "1") { email } }');
  await run('missing required arg', '{ student { name } }');
})();

Queries, variables, an alias, a mutation, a missing record and two invalid queries run against an in-memory schema. Install first with npm install graphql (run here with graphql 16.15.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): only name and grade {"data":{"student":{"name":"Asha","grade":"A"}}} variables + alias {"data":{"top":[{"name":"Asha"}]}} mutation {"data":{"addStudent":{"id":"3","name":"Meera","grade":"A"}}} unknown id (nullable) {"data":{"student":null}} unknown field {"errors":[{"message":"Cannot query field \"email\" on type \"Student\".","locations":[{"line":1,"column":22}]}]} missing required arg {"errors":[{"message":"Field \"student\" argument \"id\" of type \"ID!\" is required, but it was not provided.","locations":[{"line":1,"column":3}]}]}

Key points

  • The schema is typed and the client picks the fields.
  • A resolver runs for each field; default resolvers read properties.
  • Variables keep values out of the query text.
  • Responses can mix data and errors.
  • GraphQL reduces round trips but adds server-side complexity.

Common mistakes

  • Building queries by concatenating user input into the query string.
  • Treating GraphQL as always better than REST.
  • Returning HTTP 200 and ignoring the errors array on the client.
  • Exposing internal database errors in GraphQL errors.
  • Not thinking about N+1 resolver queries.

Follow-ups

  • What is the difference between a query and a mutation?
  • How do fragments and aliases work?
  • How do you cache GraphQL responses?

Tips

  • Describe the schema, query and resolver triple.
  • Compare with REST in two lines.
  • Mention N+1 as a known problem.