GraphQL
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more.
1. GraphQL vs REST
While REST APIs rely on multiple endpoints (URLs) to return fixed data structures, GraphQL typically exposes a single endpoint.
- REST: You might need to hit
/users/1to get user details, then/users/1/poststo get their posts. This often leads to Over-fetching (getting too much data) or Under-fetching (not getting enough in one request). - GraphQL: You send a single query describing the nested data you want (User + Posts), and the server returns exactly that.
2. Core Concepts
Schema
The schema defines the "shape" of your data graph. It specifies types and relationships.
type User {
id: ID!
name: String!
posts: [Post]
}
type Post {
id: ID!
title: String!
}
Query
A request to read or fetch data. It looks like JSON keys without values.
query {
user(id: "123") {
name
posts {
title
}
}
}
Mutation
A request to write (create, update, delete) data.
mutation {
createPost(title: "Hello World", userId: "123") {
id
title
}
}
Resolvers
Resolvers are functions written on the server that are responsible for populating the data for a single field in your schema.
3. Example Response
If you send the query above, the server returns JSON that mirrors the query structure:
{
"data": {
"user": {
"name": "Alice",
"posts": [
{ "title": "My First Post" },
{ "title": "GraphQL is Cool" }
]
}
}
}