GraphQL
Beginner
1 min read
Setting Up a GraphQL Server with Apollo
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
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL