GraphQL is a query language for APIs: the client sends one request to one endpoint, describing exactly the data it wants, and the server sends back that data and nothing else.
It matters because it changes who decides the shape of a response, from the server to the client that has to use it.
The problem with many endpoints
A typical REST API gives every resource its own URL. Picture a shop app's home screen that needs three things: the user's name, their last three orders and how many unread notifications they have. With REST that is often three requests:
GET /users/42
GET /users/42/orders?limit=3
GET /users/42/notifications?unread=trueEach one is a separate round trip, and on a slow mobile connection those trips add up. Two other problems tend to come with them:
- Over-fetching:
/users/42returns the whole user, perhaps thirty fields, when the screen needs only the name. The rest is downloaded and thrown away. - Under-fetching: the orders endpoint might return product ids rather than product names, so the app has to make more requests to fill in the gaps.
When the screen changes and needs something new, the backend team usually adds or changes an endpoint to serve it. Over time the API fills up with endpoints shaped around particular screens, such as /home-summary or /orders-with-products.
How GraphQL answers it
GraphQL puts the whole API behind a single endpoint, usually . Instead of picking a URL, the client writes a query that lists the fields it wants, nested the way it wants them. Here is the same home screen as one query:
Wondering how this was made? How we make these