GraphQL

Apollo Server 2 Introduction


Subscribe On YouTube

Apollo Server is a library which makes it easy to create a GraphQL server in JavaScript. In this tutorial we’ll walk through the steps of getting Apollo Server 2 installed, setting a new project and implementing a GraphQL server.


If you like CodingTheSmartWay, then consider supporting us via Patreon. With your help we’re able to release developer tutorial more often. Thanks a lot!


Setting Up The Project

To setup the new Apollo Server project we need to create a new empty directory first:

$ mkdir graphql-server-01

Enter the newly created project folder:

$ cd graphql-server-01

And execute the npm init command in the following way:

$ npm init --yes

By supplying option —yes we’re making sure that all questions are automatically answered with the default option (=yes) and an initial package.json file is created which enables the usage of the Node.js Package Manager (npm) to add dependencies to our project in the next step.

Installing Dependencies

Let’s add the needed dependencies to the project by executing:

$ npm install apollo-server graphql

in the project folder.

This command adds the following two packages:

  • apollo-server: This is the Apollo server library which is needed to define the shape of the data and the way data can be fetched.
  • graphql: The GraphQL JavaScript library which is needed in oder to be able to define a schema and execute GraphQL queries on that schema.

Implementing The Server

Having installed the needed dependencies we’re ready to move on and implement a first basic Apollo server.

Create a new file index.js in the project directory and insert the following code:

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

const courses = [
    {
        title: 'The Modern GraphQL Bootcamp',
        author: 'Andrew Mead',
        description: 'Learn how to build GraphQL applications using Node.js. Includes Prisma, authentication, Apollo Client, and more!',
        url: 'https://codingthesmartway.com//courses/graphql-bootcamp/'
    },
    {
        title: 'NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)',
        author: 'Maximilian Schwarzmüller',
        description: 'Master Node JS, build REST APIs with Node.js, GraphQL APIs, add Authentication, use MongoDB, SQL & much more!',
        url: 'https://codingthesmartway.com/courses/nodejs-complete-guide/'
    },
    {
        title: 'React - The Complete Guide (incl Hooks, React Router, Redux)',
        author: 'Maximilian Schwarzmüller',
        description: 'Dive in and learn React from scratch! Learn Reactjs, Hooks, Redux, React Routing, Animations, Next.js and way more!',
        url: 'https://codingthesmartway.com/courses/react-complete-guide/'
    },
];

const typeDefs = gql`
    type Course {
        title: String,
        author: String,
        description: String,
        url: String
    }

    type Query {
        courses: [Course]
    }
`;

const resolvers = {
    Query: {
        courses: () => courses
    },
};

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

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

This code is setting up Apollo Server to respond to an incoming GraphQL query request. Let’s explore what’s happing here step by step:

First ApolloServer and gql is imported from the apollo-server library. Next we’re defining an array (courses) which contains three course objects. This is the data which should be made accessible by the GraphQL API which is exposed.

Next we’re defining the shape of the data and the way in which the data can be queried by using the gql tag. To define the shape of the course data we’re adding the Course type definition which contains four properties (title, author, description, and url) of type String.

Furthermore we’re adding a Query type which contains the courses query definition. This query returns an array of Course objects and can therefore be used to retrieve a list of all available courses.

Next we need to add a resolver for our defined query. A resolver is a functions which contains the logic to return the result of the query. For the courses query we’re adding a resolver function which is just returning what’s available in the courses array.

Finally we’re able to create an instance of ApolloServer which is stored in the variable server. The ApolloServer constructor is expecting to get an object as a parameter which consists of our type definitions and resolvers.

With the instance of ApolloServer available in server we’re ready to call server.listen() to actually start the server process and make it listen for incoming GraphQL queries.

Starting The Server

With the full server code available in index.js we’re ready to start the server. Switch back to the command line and execute the following command within the project’s directory:

$ node index.js

You should then be able to see the following output:

The output is telling us that the server is ready at http://localhost:4000/.

Because we’ve been using the node command so execute our code inside of index.js we need to stop the running Node process (CTRL+C) and restart the server again if we’re changing our code.

Thus, there is an easier way by using the nodemon utility (https://github.com/remy/nodemon). Nodemon is a tool that helps develop Node.js applications by automatically restarting the application when code changes are made. In order to be able to make use of nodemon first make sure to add it globally on your system:

$ npm install -g nodemon

Once installed you can use the nodemon command to start our server in the following way:

$ nodemon index.js

The output should then correspondent to what you can see in the following screenshot:

Now the Apollo GraphQL Server is running again and every time we’re changing code in index.js the server process is restarted automatically.

Creating GraphQL Queries

With the GraphQL server up and running we’re ready to send GraphQL queries to the server.

The easiest way to do so is to use the Playground in-browser GraphQL IDE which is available via http://localhost:4000:

The Playground web application is split up into two main areas:

  • On the left an GraphQL query editor is available which is used to input your specific GraphQL query
  • On the right side you’ll find response which is returned from the Apollo Server once the query is executed

Furthermore you’re able to open up the API schema documentation by clicking on the Schema link on the right side.

Let’s write and execute our first query by inserting the following GraphQL query code in the query editor on the left side:

{
  courses {
    title
  }
}

Hit the Play button in the middle of the window to execute the query and you should be able to see a result on the right side:

The result comprises the following:

{
  "data": {
    "courses": [
      {
        "title": "The Modern GraphQL Bootcamp"
      },
      {
        "title": "NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)"
      },
      {
        "title": "React - The Complete Guide (incl Hooks, React Router, Redux)"
      }
    ]
  }
}

The result is returned in JSON format. The object is containing a data property which contains the courses array. The array is filled with three items. Each item consists of the title property with the corresponding value. So this result is containing exactly what we’ve requested.

If you want to get all Course properties returned you can extend the query like you can see in the following:

{
  courses {
    title
    description
    author
    url
  }
}

This time the resulting JSON response should look like the following:

{
  "data": {
    "courses": [
      {
        "title": "The Modern GraphQL Bootcamp",
        "description": "Learn how to build GraphQL applications using Node.js. Includes Prisma, authentication, Apollo Client, and more!",
        "author": "Andrew Mead",
        "url": "https://codingthesmartway.com//courses/graphql-bootcamp/"
      },
      {
        "title": "NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)",
        "description": "Master Node JS, build REST APIs with Node.js, GraphQL APIs, add Authentication, use MongoDB, SQL & much more!",
        "author": "Maximilian Schwarzmüller",
        "url": "https://codingthesmartway.com/courses/nodejs-complete-guide/"
      },
      {
        "title": "React - The Complete Guide (incl Hooks, React Router, Redux)",
        "description": "Dive in and learn React from scratch! Learn Reactjs, Hooks, Redux, React Routing, Animations, Next.js and way more!",
        "author": "Maximilian Schwarzmüller",
        "url": "https://codingthesmartway.com/courses/react-complete-guide/"
      }
    ]
  }
}

This time the response is containing the complete course items with all four properties.

Conclusion

Apollo Server 2 makes it very easy to setup a GraphQL server with Node.js. In this tutorial you’ve learned how to setup and install Apollo Server 2, implement a simple example and use the Apollo Server 2 Playground to send GraphQL queries to the server.

ONLINE COURSE: GraphQL with React: The Complete Developers Guide

Check out the great GraphQL with React: The Complete Developers Guide course with thousands of students already enrolled:

GraphQL with React: The Complete Developers Guide

  • Learn and master GraphQL by building real web apps with React and Node
  • Build amazing single page applications with React JS and GraphQL
  • Realize the power of building flexible data schemas
  • Master fundamental concepts behind structuring GraphQL servers
  • Be the engineer who explains how GraphQL works to everyone else, because you know the fundamentals so well

Go To Course

ONLINE COURSE: Node.js, Express & MongoDB Dev to Deployment

Check out the great Node.js, Express & MongoDB Dev to Deployment course with thousands of students already enrolled:

Node.js, Express & MongoDB Dev to Deployment

  • Learn by example building & deploying real-world Node.js applications from absolute scratch
  • Build high quality applications built with Node, Express and MongoDB
  • Create data models with Mongoose ODM
  • Learn ES6 concepts like arrow functions, template strings & promises
  • Implement authentication including local & Google OAuth strategies
  • Prepare & deploy apps to production with Heroku

Go To Course


Using and writing about best practices and latest technologies in web design & development is my passion.