Docs
Launch GraphOS Studio
Apollo Server 3 is officially deprecated, with end-of-life scheduled for 22 October 2024. Learn more about upgrading to a supported Apollo Server version.

Get started with Apollo Server


⚠️ As of 15 November 2022, Apollo Server 3 is officially deprecated, with end-of-life scheduled for 22 October 2024.

Learn more about deprecation and end-of-life.

This tutorial helps you:

  • Obtain a basic understanding of principles
  • Define a schema that represents the structure of your data set
  • Run an instance of 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 . If you're just getting started with or the Apollo platform, we recommend first completing the full-stack tutorial.

Step 1: Create a new project

  1. From your preferred development directory, create a directory for a new project and cd into it:

    mkdir graphql-server-example
    cd graphql-server-example
  2. Initialize a new Node.js project with npm (or another package manager you prefer, such as Yarn):

    npm init --yes

Your project directory now contains a package.json file.

Step 2: Install dependencies

Applications that run require two top-level dependencies:

  • apollo-server is the core library for itself, which helps you define the shape of your data and how to fetch it.
  • graphql is the library used to build a 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:

npm install apollo-server graphql

Also create an empty index.js file in your project's root directory:

touch 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 (including ) uses a schema to define the structure of data that clients can . 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:

index.js
const { ApolloServer, gql } = require('apollo-server');
// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
# Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
# This "Book" type defines the queryable fields for every book in our data source.
type Book {
title: String
author: String
}
# The "Query" type is special: it lists all of the available queries that
# clients can execute, along with the return type for each. In this
# case, the "books" query returns an array of zero or more Books (defined above).
type Query {
books: [Book]
}
`;

This snippet defines a simple, valid . Clients will be able to execute a named books, and our server will return an array of zero or more Books.

Step 4: Define your data set

Now that we've defined the structure of our data, we can define the data itself. can fetch data from any source you connect to (including a database, a REST API, a static object storage service, or even another server). For the purposes of this tutorial, we'll just hardcode some example data.

Add the following to the bottom of index.js:

index.js
const books = [
{
title: 'The Awakening',
author: 'Kate Chopin',
},
{
title: 'City of Glass',
author: 'Paul Auster',
},
];

This snippet defines a simple data set that clients can . 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 doesn't know that it should use that data set when it's executing a . To fix this, we create a resolver.

tell how to fetch the data associated with a particular type. Because our Book array is hardcoded, the corresponding is straightforward.

Add the following to the bottom of index.js:

index.js
// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
Query: {
books: () => books,
},
};

Step 6: Create an instance of ApolloServer

We've defined our schema, data set, and . Now we just need to provide this information to 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:

index.js
const {
ApolloServerPluginLandingPageLocalDefault
} = require('apollo-server-core');
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({
typeDefs,
resolvers,
csrfPrevention: true,
cache: 'bounded',
/**
* What's up with this embed: true option?
* These are our recommended settings for using AS;
* they aren't the defaults in AS3 for backwards-compatibility reasons but
* will be the defaults in AS4. For production environments, use
* ApolloServerPluginLandingPageProductionDefault instead.
**/
plugins: [
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
],
});
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});

Step 7: Start the server

We're ready to start our server! Run the following from your project's root directory:

node index.js

You should see the following output:

🚀 Server ready at http://localhost:4000/

We're up and running!

Step 8: Execute your first query

We can now execute queries on our server. To execute our first , we can use Apollo Sandbox.

Visit http://localhost:4000 in your browser. 's default landing page appears:

Apollo Server default landing page

Click Query your server to open Sandbox.

Note: If your server is deployed to an environment where NODE_ENV is set to production, is disabled by default. This prevents from working properly. To enable , set introspection: true in the options to ApolloServer'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
Apollo Sandbox

The Sandbox UI includes:

  • An panel for writing and executing queries (in the middle)
  • A Response panel for viewing results (on the right)
  • Tabs for schema exploration, search, and settings (on the left)
  • A URL bar for connecting to other (in the upper left)

Our server supports a single named books. Let's execute it!

Here's a query string for executing the books :

query GetBooks {
books {
title
author
}
}

Paste this string into the panel and click the blue button in the upper right. The results (from our hardcoded data set) appear in the Response panel:

Sandbox response panel

One of the most important concepts of is that clients can choose to only for the fields they need. Delete author from the string and execute it again. The response updates to include only the title for each book!

Combined example

You can view and fork this complete example on CodeSandbox:

Edit server-getting-started

Next steps

This example application is a great starting point for working with . Check out the following resources to learn more about the basics of schemas, , and deployment:

Want to learn how to modularize and scale a API? Check out the Apollo Federation Docs to learn how a federated architecture can create a unified supergraph that combines multiple APIs.

Previous
Introduction
Next
Choosing which package to use
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company