SyntaxStudy
Sign Up
GraphQL Setting Up a GraphQL Server with Apollo
GraphQL Beginner 1 min read

Setting Up a GraphQL Server with Apollo

Apollo Server is the most popular JavaScript GraphQL server. It integrates with Express, Fastify, and serverless runtimes, and provides built-in tooling like Apollo Sandbox—an in-browser IDE for exploring your schema. To bootstrap a server you define a schema (typeDefs), provide resolver functions, and pass both to ApolloServer. Apollo handles parsing, validation, and execution of incoming GraphQL documents automatically.
Example
// npm install @apollo/server graphql

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

// 1. Define the schema using SDL
const typeDefs = `#graphql
  type Book {
    id: ID!
    title: String!
    author: String!
    year: Int
  }

  type Query {
    books: [Book!]!
    book(id: ID!): Book
  }
`;

// 2. In-memory data
const books = [
  { id: '1', title: 'The Pragmatic Programmer', author: 'Hunt & Thomas', year: 1999 },
  { id: '2', title: 'Clean Code', author: 'Robert Martin', year: 2008 },
];

// 3. Resolvers
const resolvers = {
  Query: {
    books: () => books,
    book: (_, { id }) => books.find(b => b.id === id),
  },
};

// 4. Start server
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`Server ready at ${url}`);
// Visit http://localhost:4000 for Apollo Sandbox