Sling Academy
Home/Node.js/How to Build a GraphQL API with Node.js and Apollo Server

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

Last updated: December 29, 2023

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.

Next Article: How to Read and Write CSV Files with Node.js

Previous Article: 3 Ways to Convert Callbacks to Promises in Node.js

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates