Get started with Apollo Server
⚠️ As of 22 October 2024, Apollo Server 3 is officially end-of-life.
This tutorial helps you:
Obtain a basic understanding of GraphQL principles
Define a GraphQL schema that represents the structure of your data set
Run an instance of Apollo Server that lets you execute queries against your schema
This tutorial assumes that you are familiar with the command line and JavaScript, and that you have a recent version of Node.js (12+) installed.
This tutorial walks you through installing and configuring Apollo Server. If you're just getting started with GraphQL or the Apollo platform, we recommend first completing the full-stack tutorial.
Step 1: Create a new project
From your preferred development directory, create a directory for a new project and
cd
into it:
1mkdir graphql-server-example
2cd graphql-server-example
Initialize a new Node.js project with
npm
(or another package manager you prefer, such as Yarn):
1npm init --yes
Your project directory now contains a package.json
file.
Step 2: Install dependencies
Applications that run Apollo Server require two top-level dependencies:
apollo-server
is the core library for Apollo Server itself, which helps you define the shape of your data and how to fetch it.graphql
is the library used to build a GraphQL schema and execute queries against it.
Run the following command to install both of these dependencies and save them in
your project's node_modules
directory:
1npm install apollo-server graphql
Also create an empty index.js
file in your project's root directory:
1touch index.js
To keep things
simple, index.js
will contain all of the code for this example application.
Step 3: Define your GraphQL schema
Every GraphQL server (including Apollo Server) uses a schema to define the structure of data that clients can query. In this example, we'll create a server for querying a collection of books by title and author.
Open index.js
in your preferred editor and paste the following into it:
1const { ApolloServer, gql } = require('apollo-server');
2
3// A schema is a collection of type definitions (hence "typeDefs")
4// that together define the "shape" of queries that are executed against
5// your data.
6const typeDefs = gql`
7 # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
8
9 # This "Book" type defines the queryable fields for every book in our data source.
10 type Book {
11 title: String
12 author: String
13 }
14
15 # The "Query" type is special: it lists all of the available queries that
16 # clients can execute, along with the return type for each. In this
17 # case, the "books" query returns an array of zero or more Books (defined above).
18 type Query {
19 books: [Book]
20 }
21`;
This snippet defines a simple, valid GraphQL schema. Clients will be able to execute
a query named books
, and our server will return an array of zero or more Book
s.
Step 4: Define your data set
Now that we've defined the structure of our data, we can define the data itself. Apollo Server can fetch data from any source you connect to (including a database, a REST API, a static object storage service, or even another GraphQL server). For the purposes of this tutorial, we'll just hardcode some example data.
Add the following to the bottom of index.js
:
1const books = [
2 {
3 title: 'The Awakening',
4 author: 'Kate Chopin',
5 },
6 {
7 title: 'City of Glass',
8 author: 'Paul Auster',
9 },
10];
This snippet defines a simple data set that clients can query. Notice that the two objects in the array each match the structure of the Book
type we defined in our schema.
Step 5: Define a resolver
We've defined our data set, but Apollo Server doesn't know that it should use that data set when it's executing a query. To fix this, we create a resolver.
Resolvers tell Apollo Server how to fetch the data associated with a particular type. Because our Book
array is hardcoded, the corresponding resolver is straightforward.
Add the following to the bottom of index.js
:
1// Resolvers define the technique for fetching the types defined in the
2// schema. This resolver retrieves books from the "books" array above.
3const resolvers = {
4 Query: {
5 books: () => books,
6 },
7};
Step 6: Create an instance of ApolloServer
We've defined our schema, data set, and resolver. Now we just need to provide this information to Apollo Server when we initialize it. (We also want to enable CSRF prevention, an important security feature that is only disabled by default for reasons of backward compatibility.)
Add the following to the bottom of index.js
:
1const {
2 ApolloServerPluginLandingPageLocalDefault
3} = require('apollo-server-core');
4
5// The ApolloServer constructor requires two parameters: your schema
6// definition and your set of resolvers.
7const server = new ApolloServer({
8 typeDefs,
9 resolvers,
10 csrfPrevention: true,
11 cache: 'bounded',
12 /**
13 * What's up with this embed: true option?
14 * These are our recommended settings for using AS;
15 * they aren't the defaults in AS3 for backwards-compatibility reasons but
16 * will be the defaults in AS4. For production environments, use
17 * ApolloServerPluginLandingPageProductionDefault instead.
18 **/
19 plugins: [
20 ApolloServerPluginLandingPageLocalDefault({ embed: true }),
21 ],
22});
23
24// The `listen` method launches a web server.
25server.listen().then(({ url }) => {
26 console.log(`🚀 Server ready at ${url}`);
27});
Step 7: Start the server
We're ready to start our server! Run the following from your project's root directory:
1node index.js
You should see the following output:
1🚀 Server ready at http://localhost:4000/
We're up and running!
Step 8: Execute your first query
We can now execute GraphQL queries on our server. To execute our first query, we can use Apollo Sandbox.
Visit http://localhost:4000
in your browser. Apollo Server's default landing page appears:
Click Query your server to open Sandbox.
Note: If your server is deployed to an environment where
NODE_ENV
is set toproduction
, introspection is disabled by default. This prevents Apollo Sandbox from working properly. To enable introspection, setintrospection: true
in the options toApolloServer
's constructor.
You can also:
Select Automatically redirect to Studio next time if you want to open Sandbox automatically whenever you visit
localhost:4000
Open Sandbox directly at studio.apollographql.com/sandbox
The Sandbox UI includes:
An Operations panel for writing and executing queries (in the middle)
A Response panel for viewing query results (on the right)
Tabs for schema exploration, search, and settings (on the left)
A URL bar for connecting to other GraphQL servers (in the upper left)
Our server supports a single query named books
. Let's execute it!
Here's a GraphQL query string for executing the books
query:
1query GetBooks {
2 books {
3 title
4 author
5 }
6}
Paste this string into the Operations panel and click the blue button in the upper right. The results (from our hardcoded data set) appear in the Response panel:
One of the most important concepts of GraphQL is that clients can choose to query only for the fields they need. Delete author
from the query string and execute it again. The response updates to include only the title
field for each book!
Combined example
You can view and fork this complete example on CodeSandbox:
Next steps
This example application is a great starting point for working with Apollo Server. Check out the following resources to learn more about the basics of schemas, resolvers, and deployment:
Want to learn how to modularize and scale a GraphQL API? Check out the Apollo Federation Docs to learn how a federated architecture can create a unified supergraph that combines multiple GraphQL APIs.