How to Build a GraphQL API with Node.js and Apollo Server

Updated: December 29, 2023 By: Guest Contributor Post a comment

Building a GraphQL API with Node.js and Apollo Server is a streamlined process that gives you the power to describe your data schema and provide a unified API endpoint. In this guide, you will be taken through a comprehensive journey from setting up your Node.js environment to deploying a fully functioning GraphQL API.

The Steps

Initial Setup

First, ensure you have Node.js and npm (Node Package Manager) installed. Create a new directory for your project, and initialize a new Node.js application by running:

mkdir graphql-api && cd graphql-api
npm init -y

Installing Apollo Server and GraphQL

The Apollo Server library provides a simple way to create a GraphQL API server. To install Apollo Server along with the graphql package, run:

npm install apollo-server graphql

Defining the GraphQL Schema

Your GraphQL API schema defines the types and relationships within your data. Here is a simple example:

const typeDefs = `
type Query {
  hello: String
}`;

Creating Resolvers

Next, define the resolvers which are functions that generate a response for a GraphQL query. An example for the above schema is:

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

Setting Up Apollo Server

Instantiate Apollo Server and pass in type definitions and resolvers, then start the server:

const { ApolloServer } = require('apollo-server');

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Complete Code Example

Here is a simple application that brings everything together and starts your GraphQL API server:

const { ApolloServer } = require('apollo-server');
const gql = require('graphql-tag');

const typeDefs = gql`
type Query {
  hello: String
}`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Conclusion

You’ve just created a basic GraphQL API server using Node.js and Apollo Server. This endpoint now responds to queries at the ‘/graphql’ URI. The approach we’ve explored can be expanded with more complex types, relationships, and data fetch from databases as per your application’s needs.