5. Apollo Server
4m

Overview

Our schema is in good shape, but we need a server that can actually use it to fulfill the requests it receives!

In this lesson, we will:

  • Set up

🛠 Backend first steps

On the backend side, our first goal is to create a that can:

  1. Receive an incoming from our client
  2. Validate that against our newly created schema
  3. Populate the queried schema with mocked data
  4. Return the populated as a response

The Apollo Server library helps us implement this server quickly, painlessly, and in a production-ready way.

Adding server dependencies

To get started with our server, we'll need a couple packages first: @apollo/server, graphql and graphql-tag.

  • The @apollo/server package provides a full-fledged, spec-compliant .
  • The graphql package provides the core logic for parsing and validating queries.
  • The graphql-tag package provides the gql template literal that we'll use in a moment.

In a new terminal in the root of the project, run the following:

npm install @apollo/server graphql graphql-tag

These packages are responsible for all of the wiring we'll need to get our project up and running.

Implementing Apollo Server

In the src folder, open index.ts.

We'll start with some imports. To create our server, we'll use the @apollo/server package that we installed previously. From that package, we'll import ApolloServer. We'll also need to use the startStandaloneServer function, which we can import from the @apollo/server/standalone package.

index.ts
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";

To bring in the contents of schema.graphql, we'll need some additional imports.

index.ts
import { readFileSync } from "fs";
import path from "path";
import { gql } from "graphql-tag";

We'll use both readFileSync and the path utility to read in the contents of the schema.graphql file. The gql utility we're importing is a tagged template literal, used for wrapping strings like the schema definition we're about to import! This converts GraphQL strings into the format that Apollo libraries expect when working with and schemas, and it also enables syntax highlighting.

Just below these imports, we'll add a line that puts all of these imports together and reads in our schema file.

index.ts
const typeDefs = gql(
readFileSync(path.resolve(__dirname, "./schema.graphql"), {
encoding: "utf-8",
})
);

Next, let's set up an async function called startApolloServer. Inside, we'll create an instance of the ApolloServer class and pass it our typeDefs in its options object:

index.ts
async function startApolloServer() {
const server = new ApolloServer({ typeDefs });
}

Note: We're using shorthand property notation with implied keys, because we've named our constant with the matching key (typeDefs).

To start the server, we'll use the startStandaloneServer function, passing it the server we just initialized.

index.ts
async function startApolloServer() {
const server = new ApolloServer({ typeDefs });
startStandaloneServer(server);
}

The startStandaloneServer function returns a Promise, so we'll await the results of that call, and pull out the url property from the result.

index.ts
async function startApolloServer() {
const server = new ApolloServer({ typeDefs });
const { url } = await startStandaloneServer(server);
}

We'll also log a nice little message letting us know that our server is indeed up and running!

index.ts
async function startApolloServer() {
const server = new ApolloServer({ typeDefs });
const { url } = await startStandaloneServer(server);
console.log(`
🚀 Server is running!
📭 Query at ${url}
`);
}

Finally, let's not forget to actually call the startApolloServer function at the bottom of the file!

index.ts
startApolloServer();

Save your changes. (If your server isn't running, make sure to boot it up by running npm run dev in the terminal.)

We get the log message and...not much else! We have a running server, but that's it. Floating in the vacuum of localhost space without access to any data, it's a sad and lonely server for now. 😿

Terminal output
🚀 Server is running!
📭 Query at http://localhost:4000/

Even though our server isn't connected to any yet, we can still send it a test and get a valid response; let's investigate how in the next lesson.

Practice

Which of these are purposes of a GraphQL server?
Code Challenge!

Complete the implementation of Apollo Server below by passing in typeDefs and calling startStandaloneServer with a valid server instance.

Loading...
Loading progress

Key takeaways

  • is a library that we can use to receive queries, validate them, populate the requested , and return data back to the client.
  • We can initialize a new instance by passing in our type definitions.

Up next

Let's take our server for a spin with some mock data. In the next lesson, we'll explore a development environment that gives us everything we need to jump into our API.

Previous

Share your questions and comments about this lesson

Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.