Odyssey

Intro to GraphQL with TypeScript & Apollo Server

Course overview and setupGraphQL basicsSchema definition language (SDL)Building the schemaApollo ServerApollo Sandbox ExplorerThe listings REST APIResolversCodegenQuerying real dataQuery argumentsAdding the Amenity typeResolver chainsMutations
5. Apollo Server
2m

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 Apollo Server

🛠 Backend first steps

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

  1. Receive an incoming GraphQL query from our client
  2. Validate that query against our newly created schema
  3. Populate the queried schema fields with mocked data
  4. Return the populated fields 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 GraphQL server.
  • The graphql package provides the core logic for parsing and validating GraphQL 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 GraphQL 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 GraphQL strings like the schema definition we're about to import! This converts GraphQL strings into the format that Apollo libraries expect when working with operations 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 data sources yet, we can still send it a test query 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.

Key takeaways

  • Apollo Server is a library that we can use to receive GraphQL queries, validate them, populate the requested fields, and return data back to the client.
  • We can initialize a new Apollo Server instance by passing in our GraphQL 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 GraphQL API.

Previous
Next

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.

              Apollo Server

              An open-source library for server-side GraphQL operation handling. It can be used as a monolithic GraphQL server or a subgraph server within a supergraph.

              GraphQL server

              A server that contains a GraphQL schema and can resolve client-requested operations that are executed against that schema.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              query

              A request for specific data from a GraphQL server. Clients define the structure of the response, enabling precise and efficient data retrieval.

              query

              A request for specific data from a GraphQL server. Clients define the structure of the response, enabling precise and efficient data retrieval.

              fields

              A unit of data that belongs to a type in a schema. Every GraphQL query requests one or more fields.

              type Author {
              # id, firstName, and lastName are all fields of the Author type
              id: Int!
              firstName: String
              lastName: String
              }
              fields

              A unit of data that belongs to a type in a schema. Every GraphQL query requests one or more fields.

              type Author {
              # id, firstName, and lastName are all fields of the Author type
              id: Int!
              firstName: String
              lastName: String
              }
              GraphQL server

              A server that contains a GraphQL schema and can resolve client-requested operations that are executed against that schema.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              operations

              A single query, mutation, or subscription that clients send to a GraphQL server to request or manipulate data.

              query

              A request for specific data from a GraphQL server. Clients define the structure of the response, enabling precise and efficient data retrieval.

              Apollo Server

              An open-source library for server-side GraphQL operation handling. It can be used as a monolithic GraphQL server or a subgraph server within a supergraph.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              fields

              A unit of data that belongs to a type in a schema. Every GraphQL query requests one or more fields.

              type Author {
              # id, firstName, and lastName are all fields of the Author type
              id: Int!
              firstName: String
              lastName: String
              }
              Apollo Server

              An open-source library for server-side GraphQL operation handling. It can be used as a monolithic GraphQL server or a subgraph server within a supergraph.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              GraphQL

              An open-source query language and specification for APIs that enables clients to request specific data, promoting efficiency and flexibility in data retrieval.

              NEW COURSE ALERT

              Introducing Apollo Connectors

              Connectors are the new and easy way to get started with GraphQL, using existing REST APIs.

              Say goodbye to GraphQL servers and resolvers—now, everything happens in the schema!

              Take the course