REST often ends up being either over-fetching or under-fetching data, forcing us to create lots of auxiliary endpoints. GraphQL came to solve these problems. Today we'll go over why it's useful, what problems it solves, and in the next lectures we'll move on to integrating it with Spring Boot.
What is GraphQL?
Imagine a restaurant. You open the menu and order specific dishes, knowing exactly what you'll get. GraphQL is like a restaurant menu for your API. You describe what data you need, and the server returns exactly that (and nothing extra). This query language was developed by Facebook in 2012 to address problems they faced with REST API while working on their mobile apps. Later, in 2015, Facebook open-sourced GraphQL, and now it's used by many companies like GitHub, Shopify, and Twitter.
GraphQL is a query language for APIs and a runtime for executing those queries. Its goal is to give developers a tool to request data flexibly and efficiently.
Here are a few key characteristics of GraphQL:
- Flexible queries. You decide how much data and which fields you need.
- Strong typing. The schema defines a clear data structure, making the API predictable.
- Single endpoint. All queries and mutations go through one URL.
- Real-time support via Subscriptions.
Problems solved by GraphQL
1. Over-Fetching and Under-Fetching
Imagine you're working with a REST API to get user data. You only need their email, but the REST API returns the full user info (name, age, address, etc.). That's the over-fetching problem.
Now imagine you need user data including their latest orders. The REST API developers didn't add such an endpoint, and you have to make two requests: one to /users, another to /orders. That's the under-fetching problem.
GraphQL solves both of these. You can request exactly the data you need, even if it belongs to different entities.
Example GraphQL query:
query {
user(id: 1) {
name
email
orders {
id
total
}
}
}
This query will return only the required fields:
{
"data": {
"user": {
"name": "Ivan Ivanov",
"email": "ivan@example.com",
"orders": [
{"id": 101, "total": 300},
{"id": 102, "total": 150}
]
}
}
}
2. Unification and standardization of APIs
In REST APIs we often have a bunch of separate endpoints like /users, /orders, /products. Each has its own rules, parameters, and responses. GraphQL offers a single endpoint (/graphql) through which we make all requests. This makes the API more predictable and convenient.
3. Scalability
GraphQL makes it easy to add new features to the API without breaking old ones. The schema defines types and relationships, and any new functionality is added as a new part of the schema without needing to modify existing endpoints.
Main concepts of GraphQL
1. Strong typing
GraphQL uses strong typing to describe data. This is done via the schema, which defines all possible data types and operations available in the API. The schema becomes a contract between client and server.
Example schema:
query {
user(id: 1) {
name
email
orders {
id
total
}
}
}
Data types in GraphQL:
- Scalar: simple types like
Int,Float,String,Boolean, andID. - Object: types with nested fields (for example,
User,Order). - Enum: enumerations, for example,
Status { ACTIVE, INACTIVE }. - Input: types for sending data into mutations.
2. Queries
Queries are how you fetch data from the server. They're similar to HTTP GET requests in REST API but much more flexible. The client forms the request, picking only the fields it needs.
Example query:
query {
user(id: 1) {
name
email
}
}
3. Mutations
Mutations are used to modify data on the server—analogous to POST/PUT/PATCH in REST API. You can create, update, or delete data.
Example mutation:
mutation {
createUser(name: "Ivan Ivanov", email: "ivan@example.com") {
id
name
email
}
}
Response:
{
"data": {
"createUser": {
"id": "1",
"name": "Ivan Ivanov",
"email": "ivan@example.com"
}
}
}
4. Subscriptions
Subscriptions let clients receive real-time updates. For example, notifications about new chat messages or order status changes.
Example subscription:
subscription {
orderUpdated {
id
status
}
}
The client receives updates as soon as new data appears.
Advantages of GraphQL compared to REST
| Characteristic | GraphQL | REST |
|---|---|---|
| Query flexibility | Client requests only the data it needs | Predefined endpoint responses |
| Single endpoint | One endpoint for all operations | Multiple endpoints for different operations |
| Typing | Strong typing via a schema | No built-in schema to describe data |
| Efficiency | Minimal number of server requests | Often requires multiple requests |
History of GraphQL
It all started in 2012 when Facebook ran into performance issues with their REST API in their mobile app. They realized that REST APIs were inefficient for mobile devices, which often needed different data depending on the context. As a result, GraphQL was created to address these problems. In 2015 Facebook open-sourced GraphQL, and it quickly gained popularity in the community.
Fun fact: GraphQL was originally developed for internal use at Facebook, but then it became a driver of change in how the industry approaches APIs.
At this point we've covered the core concepts of GraphQL, its history, and the problems it solves. In the next lectures we'll set up Spring Boot to work with GraphQL and create our first application.
GO TO FULL VERSION