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
- Create a new directory for your project and navigate into it.bash
mkdir my-graphql-server cd my-graphql-server - Initialize a new Node.js project. This command creates a
package.jsonfile, which keeps track of your project's details and dependencies.bashnpm 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.
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:
- 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).
- 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.
// 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 calledBook.title: String: TheBooktype has a field namedtitle, which is of the typeString.author: String: It also has anauthorfield, which is also aString.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 namedbooks. When a client calls this query, they should expect to get back an array (indicated by the square brackets[]) ofBookobjects.
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."
// 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.
// index.js (add the resolvers)
// Resolver functions for the schema fields
export const resolvers = {
Query: {
books: () => books,
},
};It's that simple!
- The
resolversobject has aQueryproperty, which matches theQuerytype in our schema. - Inside
Query, we have a function namedbooks, which matches thebooksfield in our schema. - This function takes no arguments (for now) and simply returns our
booksarray.
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:
// 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:
{
"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:
node index.jsYou 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:
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:
{
"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.
- Apollo Server Documentation: https://www.apollographql.com/docs/apollo-server/
- GraphQL.org Introduction: https://graphql.org/learn/
- 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:
UserType:id:ID!name:String!email:String!posts:[Post](A list of posts authored by this user)
PostType:id:ID!title:String!content:StringauthorId:ID!author:User(The user who authored the post)
QueryType:users: Returns an array of allUserobjects.user(id: ID!): Returns a singleUserobject by theirid.posts: Returns an array of allPostobjects.
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
Querytype. - A resolver for the nested
postsfield on theUsertype. - A resolver for the nested
authorfield on thePosttype.
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:
- A
typeDefsconstant holding a GraphQL schema as a template literal string. This schema must accurately define theUser,Post, andQuerytypes as specified in the instructions, including all fields, their scalar types, and non-nullability. - A
resolversobject containing the logic to resolve all defined queries and fields.- It must have a
Queryproperty with resolver functions forusersanduser(id, args). These functions should correctly return data from theusersmock array. - The
Queryproperty must also include a resolver forpoststhat returns thepostsmock array. - It must include top-level
UserandPostproperties to handle the nested resolvers. - The
User.postsresolver must correctly filter thepostsarray to return only the posts written by the parentUser. - The
Post.authorresolver must correctly find and return the specific user from theusersarray that matches the parentPost'sauthorId.
- It must have a
- The script must create a new instance of
ApolloServer, passing thetypeDefsandresolversin the configuration object. - The script must call
startStandaloneServer, passing the server instance and an options object to specifylisten: { port: 4000 }.