How to Implement a GraphQL API in Node.js
This article provides a step-by-step guide on how to build and run a functional GraphQL API within a Node.js environment. You will learn how to initialize a project, install the necessary dependencies using Apollo Server, define a schema with queries, write resolvers to handle data fetching, and launch the server.
Step 1: Initialize the Project and Install Dependencies
To get started, create a new directory for your project, initialize
it, and install the required packages. You will need
@apollo/server (the industry standard for building GraphQL
servers in Node.js) and graphql.
Run the following commands in your terminal:
mkdir node-graphql-api
cd node-graphql-api
npm init -y
npm install @apollo/server graphqlOpen your package.json file and add
"type": "module" to enable ES module imports (using
import instead of require).
Step 2: Define the GraphQL Schema
The schema defines the structure of your data and the operations
clients can perform. Create a file named index.js and
define your type definitions (typeDefs) using the
gql tag.
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
// The schema defines a "Book" type and a "Query" type to fetch books
const typeDefs = `#graphql
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;Step 3: Create the Dataset and Resolvers
Resolvers are functions that tell the server how to populate the data for a specific field in your schema. For simplicity, we will use a hardcoded array as our data source.
Add the dataset and the resolvers to index.js:
// Hardcoded data source
const books = [
{
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
},
{
title: 'Wuthering Heights',
author: 'Emily Brontë',
},
];
// Resolvers define how to fetch the types defined in the schema
const resolvers = {
Query: {
books: () => books,
},
};Step 4: Configure and Start the Server
Finally, pass your schema (typeDefs) and
resolvers to an instance of ApolloServer and
start the server.
Add the following code to the bottom of index.js:
// Create the Apollo Server instance
const server = new ApolloServer({
typeDefs,
resolvers,
});
// Start the standalone server
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
});
console.log(`🚀 Server ready at: ${url}`);Step 5: Test the API
Run the application using Node.js:
node index.jsOpen your browser and navigate to http://localhost:4000.
This will open the Apollo Sandbox, an interactive playground where you
can execute queries. You can run the following query to test your
implementation:
query GetBooks {
books {
title
author
}
}