Learn GraphQL Β· 6/15

Building Your First GraphQL Server

9 min read

Welcome! So, you've heard the buzz about GraphQL and now you're ready to build your own server. Fantastic choice! Before we lay the first brick, let's understand the problem we're solving.

The Problem: In traditional REST APIs, you often have to make multiple requests to get all the data you need (e.g., one for a user, another for their posts, another for their comments). This is called "under-fetching." Or, you get a single, massive object with tons of data you don't actually need, which is "over-fetching." It's like ordering a whole cow just to get a steak. πŸ₯©

The Solution: A GraphQL server provides a single endpoint where clients can ask for exactly the data they need, no more, no less. It gives the power back to the client, making applications faster and more efficient.

In this guide, we'll build a simple GraphQL server from scratch. Let's get our tools ready!


1. πŸ”§ Environment Setup: Node.js and Apollo Server

First things first, we need a place to build and the right tools for the job. Our foundation will be Node.js, and our specialized machinery will be Apollo Server.

What is Node.js?
Node.js is a runtime environment that lets you run JavaScript on your computer, not just in a browser. This is what allows us to build the "backend" or the server-side of our application.

What is Apollo Server?
Apollo Server is a popular, open-source GraphQL server library. It's like a pre-fabricated, high-tech kitchen for our restaurant. It handles the complicated parts of receiving, parsing, and responding to GraphQL requests, letting us focus on the "menu" (our data) and the "recipes" (how to get it).

Let's get this set up.

Step 1: Initialize a Node.js Project

  1. Create a new directory for your project and navigate into it.
    bash
    mkdir my-graphql-server
    cd my-graphql-server
  2. Initialize a new Node.js project. This command creates a package.json file, which keeps track of your project's details and dependencies.
    bash
    npm init -y

Step 2: Install Dependencies

Now, we'll install Apollo Server and the core graphql library. We're grabbing the latest and greatest versions to make sure our server is up to modern standards.

bash
npm install @apollo/server graphql
  • @apollo/server: The main Apollo Server library for building the server.
  • graphql: The essential library that provides the core logic for implementing a GraphQL server.

Your package.json file will now list these as dependencies. That's it! Our workshop is now set up and ready for the real work.


2. πŸ“œ Connecting the Schema: TypeDefs and Resolvers

The Problem: Our server exists, but it's an empty shell. It has no idea what kind of data it can serve or how to retrieve that data. If a client asks for a "book," our server will just stare back blankly. πŸ€·β€β™‚οΈ

The Solution: We need to give our server two fundamental pieces of information:

  1. TypeDefs (Type Definitions): A "blueprint" or a "contract" that strictly defines what our API looks like. It lists all the types of data a client can request. This is written in the GraphQL Schema Definition Language (SDL).
  2. Resolvers: A "set of instructions" or the "how-to" guide. For every piece of data defined in the schema, there's a corresponding resolver function that tells the server how to fetch it.

Think of it like a restaurant menu. The typeDefs are the menu itself, listing the dishes you can order (Query), and describing what each dish contains (type). The resolvers are the kitchen recipes that the chef uses to actually prepare your dish when you order it.

Step 1: Define the Schema (TypeDefs)

Let's create an index.js file and define a simple schema for serving information about books.

javascript
// index.js

// The GraphQL schema
export const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

Let's break this down:

  • type Book: We're defining a new object type called Book.
  • title: String: The Book type has a field named title, which is of the type String.
  • author: String: It also has an author field, which is also a String.
  • type Query: This is a special, top-level type. It defines all the entry points for reading data from our API. Think of these as the main questions a client can ask.
  • books: [Book]: We're defining a query named books. When a client calls this query, they should expect to get back an array (indicated by the square brackets []) of Book objects.

Interesting Fact: The Query type is one of the three root operation types in GraphQL. The other two are Mutation (for writing/changing data) and Subscription (for real-time data). For now, we're just focusing on querying.


3. πŸ“š Mocking Data for Rapid Prototyping

The Problem: We've defined what data we can serve, but we haven't told our server how to get it. We could set up a whole database, but that's slow and complicated for just starting out. We need a way to test our schema and let our frontend team start building without waiting.

The Solution: We can use mock data! This is just hardcoded, dummy data that lives directly in our server code. It's a fantastic way to get up and running quickly and ensure the structure of our API is working as expected. This keeps everyone happy and productive. πŸ˜‰

Step 1: Create the Mock Data

Let's create a simple array of book objects. This will act as our temporary, in-memory "database."

javascript
// index.js (add this data)

const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
];

Step 2: Create the Resolvers

Now, we'll create the resolver map. This is a JavaScript object that mirrors the structure of our schema. For our books query, we need a resolver function that returns our books array.

javascript
// index.js (add the resolvers)

// Resolver functions for the schema fields
export const resolvers = {
  Query: {
    books: () => books,
  },
};

It's that simple!

  • The resolvers object has a Query property, which matches the Query type in our schema.
  • Inside Query, we have a function named books, which matches the books field in our schema.
  • This function takes no arguments (for now) and simply returns our books array.

Whenever a client runs the books query, Apollo Server will execute this function and return the result.


4. πŸš€ Booting Up: Starting the Server Locally

The Problem: We've written all the code. We have our schema, our mock data, and our resolvers. But right now, they're all just text in a file. The file isn't "running." We need to bring our server to life so it can actually listen for and respond to requests from the internet (or, in our case, from our own computer).

The Solution: We'll use the @apollo/server library to combine our typeDefs and resolvers into a functioning server and then tell it to start listening on a specific network port. A port is like a numbered door on our computer that our server will listen at. Port 4000 is a common choice for local development.

Step 1: Put It All Together and Start the Server

Let's complete our index.js file. We need to import the necessary pieces from @apollo/server, create a new server instance, and then start it. The most common way to do this with modern Apollo Server is using startStandaloneServer.

Here is the complete index.js file:

javascript
// index.js

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

// 1. The GraphQL schema
const typeDefs = `#graphql
  type Book {
    title: String
    author: String
  }

  type Query {
    books: [Book]
  }
`;

// 2. Mock data
const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
];

// 3. Resolver functions for the schema fields
const resolvers = {
  Query: {
    books: () => books,
  },
};

// 4. Create an instance of ApolloServer
const server = new ApolloServer({
  typeDefs,
  resolvers,
});

// 5. Start the server
const { url } = await startStandaloneServer(server, {
  listen: { port: 4000 },
});

console.log(`πŸš€  Server ready at: ${url}`);

Note: To use await at the top level like this, you might need to add "type": "module" to your package.json file, or alternatively, wrap the server startup logic in an async function and call it. Adding "type": "module" is the more modern approach.

Your package.json should look something like this:

json
{
  "name": "my-graphql-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@apollo/server": "^4.x.x", // your version will be here
    "graphql": "^16.x.x" // your version will be here
  }
}

Step 2: Run the Server

Open your terminal in the project directory and run:

bash
node index.js

You should see a glorious message in your console:
πŸš€ Server ready at: http://localhost:4000/

Congratulations! You have officially built and launched your first GraphQL server.

Step 3: Explore with Apollo Sandbox

Open your web browser and navigate to http://localhost:4000. You will be greeted by the Apollo Sandbox, an amazing, built-in web interface that lets you interact with your new API.

In the "Operation" panel on the left, type the following query:

graphql
query GetBooks {
  books {
    title
    author
  }
}

Press the "Run" button. In the "Response" panel on the right, you should see your mock data come back perfectly formatted:

json
{
  "data": {
    "books": [
      {
        "title": "The Awakening",
        "author": "Kate Chopin"
      },
      {
        "title": "City of Glass",
        "author": "Paul Auster"
      }
    ]
  }
}

Try modifying the query to only ask for the title and see what happens. This is the power of GraphQL in action! You've successfully built a server that lets the client decide exactly what data it needs.


πŸ“– Further Reading

To continue your journey, check out the official documentation. They are the ultimate source of truth and are packed with more advanced examples and guides.

  1. Apollo Server Documentation: https://www.apollographql.com/docs/apollo-server/
  2. GraphQL.org Introduction: https://graphql.org/learn/
  3. Node.js Documentation: https://nodejs.org/en/docs/

Challenge

Your task is to build a complete, self-contained GraphQL server using @apollo/server. The server should manage a collection of users and their posts based on the provided mock data.

You must implement the following components in a single script:

1. Schema Definition (TypeDefs)

Define the GraphQL schema with the following types and queries:

  • User Type:

    • id: ID!
    • name: String!
    • email: String!
    • posts: [Post] (A list of posts authored by this user)
  • Post Type:

    • id: ID!
    • title: String!
    • content: String
    • authorId: ID!
    • author: User (The user who authored the post)
  • Query Type:

    • users: Returns an array of all User objects.
    • user(id: ID!): Returns a single User object by their id.
    • posts: Returns an array of all Post objects.

2. Data Resolution (Resolvers)

Implement the resolver functions to fetch the data for each field in your schema using the provided mock data. This includes:

  • Resolvers for all fields inside the Query type.
  • A resolver for the nested posts field on the User type.
  • A resolver for the nested author field on the Post type.

3. Server Initialization

Instantiate a new ApolloServer with your typeDefs and resolvers. Then, start the server on port 4000 using startStandaloneServer.

Expected result

Your code should be a complete Node.js script that correctly sets up and starts an Apollo GraphQL server.

The final code must contain:

  1. A typeDefs constant holding a GraphQL schema as a template literal string. This schema must accurately define the User, Post, and Query types as specified in the instructions, including all fields, their scalar types, and non-nullability.
  2. A resolvers object containing the logic to resolve all defined queries and fields.
    • It must have a Query property with resolver functions for users and user(id, args). These functions should correctly return data from the users mock array.
    • The Query property must also include a resolver for posts that returns the posts mock array.
    • It must include top-level User and Post properties to handle the nested resolvers.
    • The User.posts resolver must correctly filter the posts array to return only the posts written by the parent User.
    • The Post.author resolver must correctly find and return the specific user from the users array that matches the parent Post's authorId.
  3. The script must create a new instance of ApolloServer, passing the typeDefs and resolvers in the configuration object.
  4. The script must call startStandaloneServer, passing the server instance and an options object to specify listen: { port: 4000 }.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.