What is GraphQL
Overview
GraphQL is an open-source query language for APIs and a runtime for fulfilling those queries with existing data.
This is a query language and runtime for APIs. It was developed by Facebook and is used to get and update data from a server.
Instead of having many endpoints like in REST APIs, GraphQL has just one endpoint that can handle different kinds of requests depending on what the client asks for.
In simple terms:
GraphQL is a way for your app to talk to a server and get exactly the data it needs - nothing more, nothing less.
It's an alternative to REST APIs.
Imagine this:
Think of a GraphQL server like a restaurant.
- With REST, you order fixed meals (like a "burger combo"). If you only want the burger but not the fries and drinks, too bad - you still get everything.
- With GraphQL, you tell the server exactly what you want. "I want just a burger and a cookie." And that'S what you get!
If you think you can do this using REST, read on.
How it works:
Instead of having many URLs like:
/users
/users/1/posts
/users/1/comments
You send one query to one endpoint (usually /graphql
), and you ask for what you want:
{
user(id: 1) {
name
posts {
title
}
}
}
And the server replies with only that data:
{
"data": {
"user": {
"name": "Alice",
"posts": [
{ "title": "My first post" },
{ "title": "Another post" }
]
}
}
}
Benefits:
- Ask for only the data you need
- Avoid multiple requests - just one query for everything
- Easier for frontend developers - more control
Common Terms:
- Query: To get data
- Mutation: To change data (like create, update, delete)
- Schema: A description of what data is available
- Resolver: Code that fetches the actual data
How is GraphQL different from REST?
Feature | REST | GraphQL |
---|---|---|
Endpoints | Multiple (e.g., /users , /posts ) |
One (usually /graphql ) |
Data fetching | Fixed - server decides what to return | Flexible - client decides |
Over-fetching | Common - you might get extra data | Avoided - you get only what you ask for |
Under-fetching | You might need multiple calls | One request can return nested data |
Key Concepts in GraphQL
1. Schema
- A blueprint of your API.
- Defines types (like
User
,Post
, etc.) and what fields each type has.
2. Query
- Used to get data.
{
user(id: "1") {
name
email
}
}
3. Mutation
- Used to change data (create, update, delete).
mutation {
createUser(name: "Alice", email: "[email protected]") {
id
}
}
4. Resolver
- The function that tells GraphQL how to fetch the data for a specific field in the schema.
5. Subscription (option)
- Allows real-time updates from the server (like WebSocket-based).
Why Use GraphQL?
- Only get the data you need.
- Reduce number of requests.
- Better for mobile or slow networks
- Easy to evolve API over time.
Top comments (0)