Introduction to GraphQL
If you’re familiar with REST APIs, think of GraphQL as an alternative way to fetch and manipulate data from a server. While both technologies serve similar purposes, they approach the problem differently.
Key Differences from REST
1. Single Endpoint vs Multiple Endpoints
REST: Uses multiple endpoints (URLs) like /users, /posts/{id}, /comments
GraphQL: Uses a single endpoint for all operations (typically /graphql)
Instead of making multiple requests to different endpoints, you send all your data requirements to one endpoint.
2. Request What You Need vs Fixed Responses
REST: The server decides what data to return
- Example:
GET /users/1returns a fixed structure with user data - If you only need the user’s name and email, you still get everything else too
GraphQL: You specify exactly what you want
query {
user(id: "1") {
name
email
}
}You only get the name and email fields - nothing more.
3. No Over-fetching or Under-fetching
REST Problem: You often fetch too much data (over-fetching) or need multiple requests to get related data (under-fetching)
GraphQL Solution:
- Get exactly the data you need in one request
- Fetch nested resources without additional requests
Example with nested data:
query {
user(id: "1") {
name
posts {
title
comments {
text
}
}
}
}4. Strongly Typed Schema
GraphQL has a defined schema that describes:
- What types of data are available
- What queries can be made
- What mutations can be performed
This schema serves as documentation and validation for your API.
GraphQL Operations
Queries (GET-like)
Used to fetch data:
query {
users {
id
name
email
}
}Mutations (POST/PUT/DELETE-like)
Used to modify data:
mutation {
createUser(name: "Alice", email: "alice@example.com") {
id
name
}
}