Introduction to GraphQL and Quick Start

Learn what GraphQL is, how it compares with REST, and how to build your first GraphQL service with Apollo Server and run a query.

🎯 Introduction

If you have connected a frontend to a backend, this probably sounds familiar: a page only needs a user's name and avatar, but a REST endpoint returns the entire user object, leaving most fields unused. Or a page needs three or four requests just to collect all the data it needs.

GraphQL is an approach to APIs designed to address these problems. By the end of this article, you will understand what GraphQL is, how it differs from REST, and how to run a local GraphQL service with Apollo Server and send your first query in a browser-based explorer. This setup is the foundation for the rest of the series.


🧱 What Is GraphQL?

GraphQL is a query language for APIs and a server-side runtime. Developed by Meta (formerly Facebook) and open-sourced in 2015, it is widely used in frontend and Node.js development.

Its central idea is simple: the client specifies the fields it needs, and the server returns exactly those fields.

Think of a REST endpoint as a set menu at a restaurant: you receive the predefined dishes, with no way to remove or add items. GraphQL is more like ordering à la carte: you choose the dishes, and the kitchen prepares exactly what you ordered.

A GraphQL query looks like this:

{
    users {
        username
        age
    }
}

The response closely matches the structure of the query:

{
    "data": {
        "users": [
            { "username": "Alex", "age": 20 },
            { "username": "Emma", "age": 22 }
        ]
    }
}

Request the fields you need. That is the basic way GraphQL works.


⚖️ Comparing GraphQL with REST

First, a quick look at REST. REST is an architectural style for designing APIs, rather than a protocol or library. Two central conventions are:

  • URLs identify resources: data is organized into resources with their own addresses. For example, /users represents a user list, and /users/1 represents the user with ID 1.
  • HTTP methods describe actions: for the same URL, use GET to read, POST to create, PATCH to update, and DELETE to delete.

The app.get('/users', ...) route from the Express course is an example of a REST endpoint. REST has been a mainstream approach for years and remains widely used. Comparing it with GraphQL provides a useful starting point:

AspectRESTGraphQL
API endpointsMultiple URLs (/users, /articles, etc.)Usually one endpoint, such as /graphql
Response structureDefined by the serverFields selected by the client
Related dataOften requires combining multiple requestsRetrieved through nested fields in one query
API documentationMaintained separately, for example with SwaggerThe schema serves as browsable documentation

For example, suppose a page needs a user list along with the titles of each user's articles. With REST, you might request /users, then request articles separately for each user ID. GraphQL needs just one query:

{
    users {
        username
        articles {
            title
        }
    }
}
GraphQL does not aim to replace REST. REST is straightforward, has a mature ecosystem, and works well in many situations. GraphQL is especially useful for complex data structures and clients with very different field requirements. Both are mainstream approaches; choose based on your project.

🛠 Building Your First GraphQL Service

GraphQL itself is a specification, so you need a server library to implement it. Apollo Server is a common choice in Node.js. It handles request parsing, validation, and errors, leaving you to describe the data and where it comes from.

This course was written and tested with Node.js v22 LTS, @apollo/server 5.x, and graphql 16.x. Create and initialize a project directory, then install the dependencies:

mkdir graphql-demo && cd graphql-demo
npm init -y
npm pkg set type=module
npm install @apollo/server graphql
  • npm pkg set type=module configures the project to use ESM. Apollo Server 5 requires ESM import syntax.
  • graphql is the official JavaScript implementation of the GraphQL specification, which Apollo Server depends on.

Create server.js with the following code:

server.js
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

// Mock user data
const users = [
    { id: '1', username: 'Alex', age: 20, city: 'Beijing' },
    { id: '2', username: 'Emma', age: 22, city: 'Shenzhen' },
];

// 1. Describe the data structure in GraphQL (schema)
const typeDefs = `#graphql
    type User {
        id: ID!
        username: String!
        age: Int
        city: String
    }

    type Query {
        users: [User!]!
        user(id: ID!): User
    }
`;

// 2. Provide the actual data with JavaScript functions (resolvers)
const resolvers = {
    Query: {
        users: () => users,
        user: (parent, args) => users.find((item) => item.id === args.id),
    },
};

// 3. Create and start the server
const server = new ApolloServer({ typeDefs, resolvers });

const { url } = await startStandaloneServer(server, {
    listen: { port: 4000 },
});

console.log(`Server running at: ${url}`);

This code contains the three standard parts of a GraphQL server:

  • typeDefs (schema): describes the available data and each field's type in GraphQL's own language. type Query declares the queries clients can make.
  • resolvers: JavaScript functions corresponding to schema fields that retrieve the actual data. Here they read an in-memory array; later they could query a database instead.
  • ApolloServer: combines the schema and resolvers into a service. startStandaloneServer runs it on port 4000.

Run node server.js. When you see Server running at: http://localhost:4000/, the service is ready.


✨ Sending Your First Query

Apollo Server provides a browser-based explorer called Apollo Sandbox. Open http://localhost:4000/ in your browser. Write queries on the left and view results on the right.

Enter this on the left:

{
    users {
        username
        city
    }
}

Click the run button to see the corresponding JSON on the right. Because the query requests only username and city, the response does not include age. This demonstrates field selection in action.

Next, try a query with an argument to find a single user by ID:

{
    user(id: "1") {
        username
        age
    }
}
The Apollo Sandbox interface changes periodically, so button labels and layouts may differ. Use these steps as a guide: write a query on the left and inspect the result on the right, following the interface you see.

You can also deliberately request a field that does not exist in the schema, such as hobbies:

{
    users {
        hobbies
    }
}

This time, you receive an error instead of data: Cannot query field "hobbies" on type "User". GraphQL validates queries against the schema before execution, catching unknown fields immediately rather than during execution. This is another benefit of having a schema.


❓ Questions and Answers

Q1: What does #graphql do inside typeDefs?

It is an ordinary comment that helps editors recognize the template string as GraphQL, enabling syntax highlighting and suggestions. Removing it does not affect execution, but keeping it is recommended.

Q2: Why can the outermost query omit a keyword?

{ users { ... } } is shorthand for query { users { ... } }. The query keyword identifies a query operation, the most common operation type, and can be omitted here. Later, we will use mutation to modify data.

Q3: Why hard-code data in an array? What about real projects?

An in-memory array makes the examples easy to follow. A resolver is just a function: it can query MySQL or MongoDB, or call another API, without changing anything for the client.

Q4: Is GraphQL a frontend or backend technology?

It involves both. The backend defines the schema and provides data, which is this course's main focus. The frontend writes GraphQL queries and consumes the data, as covered in the final article.

Q5: What if port 4000 is already in use?

Change listen: { port: 4000 } to another port, such as 4001, and update the URL in your browser accordingly.


🧪 Exercises

Exercise 1: Add your own entry to the users array and restart the server. In Sandbox, query only username for every user, without requesting any other fields.

# Write your code here

Exercise 2: Following the pattern of user(id: ID!): User, work out what to add to typeDefs and resolvers to query a user by username, then implement it.

server.js
// Write your code here

🎉 You have run your first GraphQL service and learned how to request exactly the fields you need! Next, we will explore the schema's type system and describe more complex data structures.