Loading
All articles
Programming 20 min read

Getting Started with GraphQL and Express: A Visual, Hands-On Guide

Build your first GraphQL API with Express, step by step: schemas, types, resolvers, arguments, nested data, mutations and variables, the GraphiQL playground, real responses, a REST comparison with measured bytes and requests, and exercises with answers.

nbkhope
On this page

A phone app shows a list of fruits with their recipes. With a classic REST API, it might call /fruits, then /fruits/1/recipes, /fruits/2/recipes, and so on, and every response carries fields the screen never shows. GraphQL turns that around: the app sends one request describing exactly the data it wants, and the server answers with exactly that shape, nothing more and nothing less.

In this guide you'll build a GraphQL API with Node.js and Express, one step at a time: a first query, your own types, arguments, nested data, mutations and variables, plus the in-browser GraphiQL playground. Along the way you'll see every real response, measure what GraphQL saves compared with REST, and finish with exercises.

All the responses below come from real runs with Node.js 26, Express 5.3, graphql 16.14, graphql-http 1.23 and Ruru 2.0.

REST vs. GraphQL in one picture

REST vs. GraphQL for a screen that lists fruits with their recipes. With REST, the app makes one request to /fruits, then one more per fruit to /fruits/1/recipes, /fruits/2/recipes and /fruits/3/recipes: 4 round trips, and each response includes every field whether the screen uses it or not. With GraphQL, the app sends a single POST to /graphql with a query naming exactly the fields it wants, fruits with name and recipes with name, and gets one response in exactly that shape. REST has many endpoints with fixed responses; GraphQL has one endpoint and the client chooses the fields

REST APIs have many endpoints, each returning a fixed shape. That leads to two problems:

  • Over-fetching: responses include fields the app doesn't need, which wastes bandwidth, especially on slow mobile connections.
  • Under-fetching: one response isn't enough, so the app makes extra round trips to gather the rest.

GraphQL has one endpoint, usually POST /graphql. The client sends a query that lists the fields it wants, and a schema on the server describes everything that can be asked for.

How a GraphQL request flows

How a GraphQL request flows through an Express server. 1: the client sends POST /graphql with a JSON body holding the query text. 2: Express routes it to the graphql-http handler. 3: GraphQL parses the query text. 4: it validates the query against the schema; unknown fields or missing arguments stop here with an errors response. 5: it executes the query, calling a resolver function for each field asked for. 6: it sends back JSON with a data key shaped exactly like the query

You write two things: the schema (what can be asked for, with types) and the resolvers (functions that fetch each field's value). Parsing, validating and shaping the response is done for you.

Setting up

Create a project and install four packages:

1mkdir fruit-api
2cd fruit-api
3npm init -y
4npm install express graphql graphql-http ruru
  • express: the web server.
  • graphql: the reference GraphQL implementation for JavaScript (schemas, types, execution).
  • graphql-http: connects GraphQL to Express, handling POST /graphql requests.
  • ruru: serves GraphiQL, the in-browser playground for trying queries.

Your first schema

Start with the smallest possible API: one field, fruit, that always answers "Banana". Put it in schema.js:

1// schema.js
2const { GraphQLObjectType, GraphQLSchema, GraphQLString } = require("graphql");
3
4const QueryType = new GraphQLObjectType({
5  name: "Query",
6  fields: {
7    fruit: {
8      type: GraphQLString,
9      resolve() {
10        return "Banana";
11      },
12    },
13  },
14});
15
16module.exports = new GraphQLSchema({ query: QueryType });
  • The Query type is the entry point: its fields are the things clients can ask for.
  • Each field has a type (here a string) and a resolve function that produces its value.

Now the server, in server.js:

1// server.js
2const express = require("express");
3const { createHandler } = require("graphql-http/lib/use/express");
4const { ruruHTML } = require("ruru/server");
5const schema = require("./schema");
6
7const app = express();
8const PORT = 3000;
9
10app.all("/graphql", createHandler({ schema }));
11
12app.get("/", (request, response) => {
13  response.type("html");
14  response.end(ruruHTML({ endpoint: "/graphql" }));
15});
16
17app.listen(PORT, () => {
18  console.log(`GraphQL server running at http://localhost:${PORT}/graphql`);
19});

createHandler({ schema }) is the whole GraphQL integration: every request to /graphql goes through it. The second route serves the GraphiQL playground at the home page (more on that soon). Start it:

$ node server.js
GraphQL server running at http://localhost:3000/graphql

A GraphQL request is an ordinary HTTP POST with a JSON body containing the query text. You can send one with curl from a second terminal:

$ curl -X POST http://localhost:3000/graphql -H "Content-Type: application/json" -d '{"query": "{ fruit }"}'
{"data":{"fruit":"Banana"}}

The query { fruit } asks for the fruit field, and the answer comes back under a data key in the same shape.

A tiny client

Quoting JSON on the command line gets old fast (and differs between shells), so here's a small Node.js client, ask.js, that sends a query and prints the response nicely:

1// ask.js: sends a GraphQL query to the server and prints the answer
2async function ask(query, variables) {
3  const response = await fetch("http://localhost:3000/graphql", {
4    method: "POST",
5    headers: { "Content-Type": "application/json" },
6    body: JSON.stringify({ query, variables }),
7  });
8  console.log(JSON.stringify(await response.json(), null, 2));
9}
10
11ask(process.argv[2], process.argv[3] && JSON.parse(process.argv[3]));
1$ node ask.js "{ fruit }"
2{
3  "data": {
4    "fruit": "Banana"
5  }
6}

This is exactly what a web or mobile app does under the hood: fetch a POST with the query.

Trying queries in GraphiQL

Open http://localhost:3000/ in your browser and you get GraphiQL (served by Ruru): type a query on the left, press the play button, and the response appears on the right. It autocompletes field names from your schema and underlines mistakes as you type. Here it's running a query from later in this guide:

The GraphiQL playground served by Ruru at localhost:3000. On the left, the query FruitWithRecipes asks for fruit with id "1" and its name, calories, and recipes with name and minutes. On the right, the JSON response: data, fruit, name "Banana", calories 89, and recipes "Banana bread" with 70 minutes and "Banana smoothie" with 5 minutes. A play button runs the query; side buttons prettify, merge and copy it, and a Docs explorer lets you browse the schema

Creating your own type

A single string isn't very interesting. Let's turn the fruit into an object with several fields, using a new GraphQLObjectType:

1// schema.js
2const {
3  GraphQLBoolean,
4  GraphQLID,
5  GraphQLInt,
6  GraphQLObjectType,
7  GraphQLSchema,
8  GraphQLString,
9} = require("graphql");
10
11const FruitType = new GraphQLObjectType({
12  name: "Fruit",
13  fields: {
14    id: { type: GraphQLID },
15    name: { type: GraphQLString },
16    description: { type: GraphQLString },
17    isTasty: { type: GraphQLBoolean },
18    calories: { type: GraphQLInt },
19  },
20});
21
22const QueryType = new GraphQLObjectType({
23  name: "Query",
24  fields: {
25    fruit: {
26      type: FruitType,
27      resolve() {
28        return {
29          id: "1",
30          name: "Banana",
31          description: "Sweet and easy to peel",
32          isTasty: true,
33          calories: 89,
34        };
35      },
36    },
37  },
38});
39
40module.exports = new GraphQLSchema({ query: QueryType });

Each field gets one of GraphQL's built-in scalar types: GraphQLID (a unique identifier, always sent as a string), GraphQLString, GraphQLBoolean, GraphQLInt, and GraphQLFloat for decimals. The fruit field's type is now FruitType, and its resolver returns an object. The fields have no resolvers of their own: GraphQL's default resolver simply reads the property with the same name from that object.

Restart the server (stop it with Ctrl+C and run node server.js again) and ask for every field:

1$ node ask.js "{ fruit { id name description isTasty calories } }"
2{
3  "data": {
4    "fruit": {
5      "id": "1",
6      "name": "Banana",
7      "description": "Sweet and easy to peel",
8      "isTasty": true,
9      "calories": 89
10    }
11  }
12}

Now the magic part. Ask for just two fields:

1$ node ask.js "{ fruit { id name } }"
2{
3  "data": {
4    "fruit": {
5      "id": "1",
6      "name": "Banana"
7    }
8  }
9}
The query's shape is the response's shape. The query fruit with id and name, on the left, produces a response on the right where fruit holds exactly id "1" and name "Banana". The fields not asked for, description, isTasty and calories, are not sent at all. Every field you list appears in the answer, in the same nesting; every field you leave out costs nothing

You get exactly the fields you asked for. A product page could ask for everything; a list screen could ask for id and name only, from the same API.

A real API: lists, arguments and nested data

Real APIs serve many records, look things up by ID, and connect records to each other. Let's keep the data in its own file, a stand-in for a database:

1// data.js: an in-memory "database" for the examples
2const fruits = [
3  { id: "1", name: "Banana", description: "Sweet and easy to peel", isTasty: true, calories: 89 },
4  { id: "2", name: "Apple", description: "Crunchy and juicy", isTasty: true, calories: 52 },
5  { id: "3", name: "Durian", description: "Famous for its strong smell", isTasty: false, calories: 147 },
6];
7
8const recipes = [
9  { fruitId: "1", name: "Banana bread", minutes: 70 },
10  { fruitId: "1", name: "Banana smoothie", minutes: 5 },
11  { fruitId: "2", name: "Apple pie", minutes: 90 },
12];
13
14module.exports = { fruits, recipes };

And the full schema:

1// schema.js
2const {
3  GraphQLBoolean,
4  GraphQLID,
5  GraphQLInt,
6  GraphQLList,
7  GraphQLNonNull,
8  GraphQLObjectType,
9  GraphQLSchema,
10  GraphQLString,
11} = require("graphql");
12const { fruits, recipes } = require("./data");
13
14const RecipeType = new GraphQLObjectType({
15  name: "Recipe",
16  fields: {
17    name: { type: GraphQLString },
18    minutes: { type: GraphQLInt },
19  },
20});
21
22const FruitType = new GraphQLObjectType({
23  name: "Fruit",
24  fields: {
25    id: { type: new GraphQLNonNull(GraphQLID) },
26    name: { type: new GraphQLNonNull(GraphQLString) },
27    description: { type: GraphQLString },
28    isTasty: { type: GraphQLBoolean },
29    calories: { type: GraphQLInt },
30    recipes: {
31      type: new GraphQLList(RecipeType),
32      resolve(fruit) {
33        return recipes.filter((recipe) => recipe.fruitId === fruit.id);
34      },
35    },
36  },
37});
38
39const QueryType = new GraphQLObjectType({
40  name: "Query",
41  fields: {
42    fruits: {
43      type: new GraphQLList(FruitType),
44      resolve() {
45        return fruits;
46      },
47    },
48    fruit: {
49      type: FruitType,
50      args: {
51        id: { type: new GraphQLNonNull(GraphQLID) },
52      },
53      resolve(parent, args) {
54        return fruits.find((fruit) => fruit.id === args.id);
55      },
56    },
57  },
58});
59
60const MutationType = new GraphQLObjectType({
61  name: "Mutation",
62  fields: {
63    addFruit: {
64      type: FruitType,
65      args: {
66        name: { type: new GraphQLNonNull(GraphQLString) },
67        calories: { type: GraphQLInt },
68      },
69      resolve(parent, args) {
70        const fruit = { id: String(fruits.length + 1), name: args.name, calories: args.calories, isTasty: true };
71        fruits.push(fruit);
72        return fruit;
73      },
74    },
75  },
76});
77
78module.exports = new GraphQLSchema({ query: QueryType, mutation: MutationType });

New ideas, one by one:

  • GraphQLList(FruitType) means "a list of fruits".
  • GraphQLNonNull(…) means "never null": every fruit always has an id and a name, and the id argument is required.
  • args declares the arguments a field accepts; the resolver receives them as its second parameter, args.
  • Nested resolvers: recipes has its own resolver, and its first parameter is the parent object, the fruit being resolved. That's how GraphQL walks from a fruit to its recipes.
  • Mutation holds fields that change data (more on that below).

Restart the server and try a list:

1$ node ask.js "{ fruits { name calories } }"
2{
3  "data": {
4    "fruits": [
5      {
6        "name": "Banana",
7        "calories": 89
8      },
9      {
10        "name": "Apple",
11        "calories": 52
12      },
13      {
14        "name": "Durian",
15        "calories": 147
16      }
17    ]
18  }
19}

Look up one fruit by ID and its recipes in the same request:

1$ node ask.js '{ fruit(id: "1") { name recipes { name minutes } } }'
2{
3  "data": {
4    "fruit": {
5      "name": "Banana",
6      "recipes": [
7        {
8          "name": "Banana bread",
9          "minutes": 70
10        },
11        {
12          "name": "Banana smoothie",
13          "minutes": 5
14        }
15      ]
16    }
17  }
18}

(The single quotes around the query keep the shell from eating the double quotes inside it. In PowerShell, wrap the query in single quotes too.)

The fruit API's schema as a graph. The Query type has two fields: fruits, a list of Fruit, and fruit(id: ID!), a single Fruit. The Mutation type has addFruit(name: String!, calories: Int), returning a Fruit. The Fruit type has id: ID!, name: String!, description: String, isTasty: Boolean, calories: Int and recipes, a list of Recipe. The Recipe type has name: String and minutes: Int. A query is a path through this graph: Query, then fruit, then recipes

The schema in GraphQL's own language

Our schema is built from JavaScript objects, but GraphQL has its own compact Schema Definition Language (SDL), and the graphql package can print ours in it:

1// print-schema.js
2const { printSchema } = require("graphql");
3const schema = require("./schema");
4
5console.log(printSchema(schema));
1$ node print-schema.js
2type Query {
3  fruits: [Fruit]
4  fruit(id: ID!): Fruit
5}
6
7type Fruit {
8  id: ID!
9  name: String!
10  description: String
11  isTasty: Boolean
12  calories: Int
13  recipes: [Recipe]
14}
15
16type Recipe {
17  name: String
18  minutes: Int
19}
20
21type Mutation {
22  addFruit(name: String!, calories: Int): Fruit
23}

[Fruit] is a list and ! means non-null. This is the notation you'll see in GraphQL documentation everywhere, and many libraries let you write the schema this way from the start.

When things go wrong

GraphQL checks every query against the schema before running any resolver. Ask for a field that doesn't exist:

1$ node ask.js "{ fruits { name color } }"
2{
3  "errors": [
4    {
5      "message": "Cannot query field \"color\" on type \"Fruit\".",
6      "locations": [
7        {
8          "line": 1,
9          "column": 17
10        }
11      ]
12    }
13  ]
14}

Forget a required argument:

1$ node ask.js "{ fruit { name } }"
2{
3  "errors": [
4    {
5      "message": "Field \"fruit\" argument \"id\" of type \"ID!\" is required, but it was not provided.",
6      "locations": [
7        {
8          "line": 1,
9          "column": 3
10        }
11      ]
12    }
13  ]
14}

The response has an errors key instead of data, with the line and column of the problem. But a valid question with no answer isn't an error: asking for a fruit that doesn't exist gives null:

1$ node ask.js '{ fruit(id: "9") { name } }'
2{
3  "data": {
4    "fruit": null
5  }
6}

Changing data: mutations

Queries read; mutations write. They're declared on the Mutation type and called with the mutation keyword. Like a query, a mutation chooses which fields of the result it wants back:

1$ node ask.js 'mutation { addFruit(name: "Mango", calories: 60) { id name calories } }'
2{
3  "data": {
4    "addFruit": {
5      "id": "4",
6      "name": "Mango",
7      "calories": 60
8    }
9  }
10}

(Our "database" is an array in memory, so the mango disappears when the server restarts. A real resolver would save it to a database.)

Variables

Real apps don't paste values into the query text. They write the query once with variables, marked with $, and send the values separately as JSON:

1$ node ask.js 'query FruitById($id: ID!) { fruit(id: $id) { name calories } }' '{"id": "4"}'
2{
3  "data": {
4    "fruit": {
5      "name": "Mango",
6      "calories": 60
7    }
8  }
9}

FruitById is the operation name (handy in logs and in GraphiQL's tabs), and $id: ID! declares the variable and its type. Our ask.js sends the second argument as the request's variables. Keeping values out of the query text is also safer, for the same reason you don't build SQL by gluing strings together.

How much does GraphQL save?

We added two REST-style routes to the same server (GET /fruits returning full fruits and GET /fruits/:id/recipes) and measured two screens:

GraphQL vs. REST for two screens, measured on this article's fruit API with Node.js 26 and Express 5.3. Screen 1, a list of fruit names: REST makes 1 request and downloads 287 bytes; GraphQL makes 1 request and downloads 74 bytes, about 74% less. Screen 2, fruit names with their recipe names: REST makes 4 requests, one for the fruits plus one per fruit, and downloads 443 bytes; GraphQL makes 1 request and downloads 183 bytes. The REST request count grows with the number of fruits: 1 + N. GraphQL stays at 1. With real APIs, whose records often have dozens of fields, the savings are usually bigger
ScreenREST requestsREST bytesGraphQL requestsGraphQL bytes
Fruit names1287174
Fruit names with recipe names44431183

For the names list, GraphQL sent about a quarter of the bytes. For names with recipes, REST needed one request per fruit on top of the list (1 + N, the infamous "N+1" pattern), while GraphQL needed one. On a phone, each extra round trip can add tens or hundreds of milliseconds, so that difference often matters more than the bytes.

Your turn: practice

Try these before peeking at the answers. Use the full API from "A real API" above, freshly restarted.

Exercise 1: Predict the response (warm-up). What does this query return?

{ fruit(id: "2") { name isTasty } }

Exercise 2: Add a field. Give every fruit a color (yellow, red and green) and make it queryable, so that { fruits { name color } } works.

Exercise 3: An empty list. Write a query for the durian's calories and the names of its recipes. What do you expect for recipes?

Exercise 4: Spot the error. Why is this query rejected?

{ fruits }

Exercise 5: Filter with an argument (challenge). Add an optional maxCalories argument to fruits, so that { fruits(maxCalories: 100) { name calories } } only returns fruits with at most 100 calories, while { fruits { name } } still returns all of them.

Quick quiz

  1. How many endpoints does a typical GraphQL API have?
  2. What's the difference between the schema and the resolvers?
  3. What does ! mean in ID!?
  4. What's the first parameter of a nested resolver like recipes?
  5. When should you use a mutation instead of a query?

Answers

Exercise 1: Only the two fields asked for, for the fruit with ID 2:

1$ node ask.js '{ fruit(id: "2") { name isTasty } }'
2{
3  "data": {
4    "fruit": {
5      "name": "Apple",
6      "isTasty": true
7    }
8  }
9}

Exercise 2: Add the data in data.js and one line to FruitType. The default resolver reads color straight from each object:

  { id: "1", name: "Banana", description: "Sweet and easy to peel", isTasty: true, calories: 89, color: "yellow" },
  { id: "2", name: "Apple", description: "Crunchy and juicy", isTasty: true, calories: 52, color: "red" },
  { id: "3", name: "Durian", description: "Famous for its strong smell", isTasty: false, calories: 147, color: "green" },
    calories: { type: GraphQLInt },
    color: { type: GraphQLString },
1$ node ask.js "{ fruits { name color } }"
2{
3  "data": {
4    "fruits": [
5      {
6        "name": "Banana",
7        "color": "yellow"
8      },
9      {
10        "name": "Apple",
11        "color": "red"
12      },
13      {
14        "name": "Durian",
15        "color": "green"
16      }
17    ]
18  }
19}

Exercise 3: No recipe has the durian's ID, so filter returns an empty array, and GraphQL sends an empty list (not null, and not an error):

1$ node ask.js '{ fruit(id: "3") { name calories recipes { name } } }'
2{
3  "data": {
4    "fruit": {
5      "name": "Durian",
6      "calories": 147,
7      "recipes": []
8    }
9  }
10}

Exercise 4: fruits is a list of objects, and GraphQL never guesses which fields you want: you must list at least one.

1$ node ask.js "{ fruits }"
2{
3  "errors": [
4    {
5      "message": "Field \"fruits\" of type \"[Fruit]\" must have a selection of subfields. Did you mean \"fruits { ... }\"?",
6      "locations": [
7        {
8          "line": 1,
9          "column": 3
10        }
11      ]
12    }
13  ]
14}

Exercise 5: Declare the argument without GraphQLNonNull so it's optional, and filter only when it's given:

1    fruits: {
2      type: new GraphQLList(FruitType),
3      args: {
4        maxCalories: { type: GraphQLInt },
5      },
6      resolve(parent, args) {
7        if (args.maxCalories === undefined) return fruits;
8        return fruits.filter((fruit) => fruit.calories <= args.maxCalories);
9      },
10    },
1$ node ask.js "{ fruits(maxCalories: 100) { name calories } }"
2{
3  "data": {
4    "fruits": [
5      {
6        "name": "Banana",
7        "calories": 89
8      },
9      {
10        "name": "Apple",
11        "calories": 52
12      }
13    ]
14  }
15}
1$ node ask.js "{ fruits { name } }"
2{
3  "data": {
4    "fruits": [
5      {
6        "name": "Banana"
7      },
8      {
9        "name": "Apple"
10      },
11      {
12        "name": "Durian"
13      }
14    ]
15  }
16}

Quiz: (1) One, usually /graphql. (2) The schema describes what can be asked for and its types; resolvers are the functions that produce each field's value. (3) Non-null: the value is always present (for an argument, it's required). (4) The parent object, here the fruit whose recipes are being resolved. (5) When the operation changes data (creating, updating or deleting); queries only read.

Cheat sheet

I want to…Write
Install the packagesnpm install express graphql graphql-http ruru
Mount GraphQL in Expressapp.all("/graphql", createHandler({ schema }))
Serve the GraphiQL playgroundresponse.end(ruruHTML({ endpoint: "/graphql" }))
Define an object typenew GraphQLObjectType({ name: "Fruit", fields: { … } })
A list / a required valuenew GraphQLList(FruitType) / new GraphQLNonNull(GraphQLID)
Accept argumentsargs: { id: { type: new GraphQLNonNull(GraphQLID) } }
Resolve a fieldresolve(parent, args) { return … }
Query some fields{ fruits { name calories } }
Pass an argument{ fruit(id: "1") { name } }
Change datamutation { addFruit(name: "Mango") { id } }
Use variablesquery FruitById($id: ID!) { fruit(id: $id) { name } } plus {"id": "1"}
See the schema as SDLprintSchema(schema)

Wrapping up

GraphQL lets each client ask for exactly the data it needs, in one request:

  • One endpoint, many shapes: the client's query decides which fields come back, and the response mirrors the query.
  • The schema is the contract: types, lists ([Fruit]), non-null values (!) and arguments, all checked before anything runs.
  • Resolvers fetch the data, field by field; nested resolvers receive their parent object.
  • Mutations change data, and variables keep values out of the query text.
  • GraphiQL gives you autocomplete and live documentation for free.
  • It can save a lot: in our measurements, a quarter of the bytes for a list screen, and 1 request instead of 1 + N for nested data.
  • Use graphql-http, not the deprecated express-graphql.

New to the language behind it? Read What Is the JavaScript Programming Language?.

Read The Road to GraphQL to deep dive into the world of GraphQL!

Thanks for reading!

Know someone who would enjoy this? Send it their way.

More articles

Read next

Programming 4 min read

Ruby Blocks and Iterators: Write Your Own

Learn how Ruby methods receive blocks, pass values with yield, handle a missing block, and return an Enumerator. Build and run your own iterator.

nbkhope
Programming 6 min read

C++ std::vector: Size, Capacity, and Safe Growth

Learn how std::vector grows in C++: the difference between size and capacity, when reserve helps, why resize is different, and how growth can invalidate references.

nbkhope
Programming 5 min read

How to Handle Errors in Go: A Hands-On Guide

Learn Go's everyday error pattern with runnable examples: return an error, check it, add context with %w, and recognize a missing file with errors.Is.

nbkhope

Comments

Be kind and specific. Comments with links from new accounts appear after a moderator reviews them.