What is GraphQL?
GraphQL is a query language for APIs that allows clients to request exactly the data they need. Unlike REST, GraphQL uses a single endpoint and lets clients specify their data requirements.
Setting Up GraphQL Server
npm install apollo-server express graphql
// server.js
const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type Query {
users: [User!]!
user(id: ID!): User
posts: [Post!]!
}
type Mutation {
createUser(name: String!, email: String!): User!
createPost(title: String!, content: String!, authorId: ID!): Post!
}
`;
const resolvers = {
Query: {
users: () => users,
user: (parent, args) => users.find(u => u.id === args.id),
posts: () => posts
},
Mutation: {
createUser: (parent, args) => {
const user = { id: String(users.length + 1), ...args, posts: [] };
users.push(user);
return user;
},
createPost: (parent, args) => {
const post = { id: String(posts.length + 1), ...args };
posts.push(post);
return post;
}
},
User: {
posts: (parent) => posts.filter(p => p.authorId === parent.id)
}
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
server.applyMiddleware({ app });
app.listen(4000, () => {
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
});
Querying GraphQL
# Query example
query {
users {
id
name
email
posts {
title
content
}
}
}
# Mutation example
mutation {
createUser(name: "John", email: "john@example.com") {
id
name
}
}
Advantages of GraphQL
- Efficient: Fetch only needed data
- Type-safe: Strong typing system
- Single endpoint: One endpoint for all operations
- Real-time: Built-in subscriptions support