Apollo server - Installation

Apollo Server can be used with several popular libraries for Node.js like Express, Koa, Hapi. It is agnostic to libraries, so it's possible to connect it with different third-party libraries in client and server applications.

In this tutorial, we will use Express.js, because it is the most popular and common middleware library for Node.js.

First install apollo-server and the express middleware library

npm install apollo-server apollo-server-express --save

Apart from these libraries for Apollo Server, we need the core libraries for Express and GraphQL:

npm install express cors graphql --save

Now every library is set to get started with the source code in the src/index.js file. First, you have to import the necessary parts for getting started with Apollo Server in Express:

import cors from 'cors';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';

Second, use both imports for initializing your Apollo Server with Express:

import express from 'express';
import { ApolloServer } from 'apollo-server-express';

const app = express();
app.use(cors())

const schema = ...
const resolvers = ...

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

server.applyMiddleware({ app, path: '/graphql' });

app.listen({ port: 8000 }, () => {
  console.log('Apollo Server on http://localhost:8000/graphql');
});

Using Apollo Server's applyMiddleware() method, we can opt-in any middleware, which in this case is Express. We specify the path for your GraphQL API endpoint, the Express application gets initialized.

The only missing items are the definition for the schema and resolvers for creating the Apollo Server instance. We'll implement them first and learn about them after:

import cors from 'cors'
import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';

const app = express();
app.use(cors())

const schema = gql`
  type Query {
    me: User
  }
  type User {
    username: String!
  }
`;
const resolvers = {
  Query: {
    me: () => {
      return {
        username: 'Henrik Grönvall',
      };
    },
  },
};

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

server.applyMiddleware({ app, path: '/graphql' });

app.listen({ port: 8000 }, () => {
  console.log('Apollo Server on http://localhost:8000/graphql');
});

The GraphQL schema provided makes up the data for reading and writing operations via GraphQL.

The schema consists of type definitions, starting with a mandatory top level Query type for reading data, followed by fields and nested fields. In the schema we have defined me field which is of the object type User. The User type has only a username field, a scalar type of string.

There are various scalar types in the GraphQL specification for defining strings (String), booleans (Boolean), integers (Int), and more.

At some point, the schema has to end at its leaf nodes with scalar types to resolve everything properly.

In the GraphQL schema, resolvers are used to return data for fields from the schema. The data source doesn't matter, because the data can be hardcoded, can come from a database, or from another (RESTful) API endpoint.

Resolvers are agnostic according to where the data comes from, which separates GraphQL from your typical database query language.

In the example above, the resolver returns an object with a username property of type string.

To verify it without a client application, Apollo Server comes with GraphQL Playground, a built-in client for consuming GraphQL APIs. It is found by using a GraphQL API endpoint in a browser at http://localhost:8000/graphql.

Define a GraphQL query to see its result:

{
  me {
    username
  }
}

The result for the query should look like this or your defined sample data:

{
  "data": {
    "me": {
      "username": "Henrik Grönvall"
    }
  }
}

Now, after installation is done, you can play with the schema, add mor fields, change resolvers and test more queries.


Published: 2020-02-10
Author: Henrik Grönvall
Henrik Grönvall
Copyright © 2022 Henrik Grönvall Consulting AB