Set up Apollo Server, define types in SDL, write your first resolvers, and explore the API in GraphiQL.
With REST, you get what the server decides to give you. With GraphQL, the client specifies exactly what it needs. No over-fetching (getting more data than needed). No under-fetching (needing multiple requests to get everything).
npm init -y
npm install @apollo/server graphql
# Create server.jsimport { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
// Schema Definition Language (SDL)
const typeDefs = `#graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
body: String
author: User!
}
type Query {
users: [User!]!
user(id: ID!): User
posts: [Post!]!
}
`;
const users = [
{ id: '1', name: 'Alice', email: '[email protected]' },
{ id: '2', name: 'Bob', email: '[email protected]' },
];
const resolvers = {
Query: {
users: () => users,
user: (_, { id }) => users.find(u => u.id === id),
},
User: {
posts: (user) => posts.filter(p => p.authorId === user.id),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`Server ready at ${url}`);! in GraphQL types means non-null. String! = never null. [Post!]! = non-null array of non-null posts. Use non-null as much as possible — it makes client code cleaner and prevents null checks everywhere.! = non-null.