What is GraphQL?
GraphQL is a query language for your API. Facebook made it a replacement for REST APIs, which are usually used to get information from servers. In a GraphQL API, the client specifies the data it needs in a query.
The server then returns the requested data, which can be more efficient than a REST API because the server is not returning more data than the client needs. GraphQL lets the client say how the data it needs should look, so the server can send back precisely what the client asked for.
This makes it easy for the client to get the data it needs without having to make multiple API calls or handle additional data that it doesn’t need.
Why do we need GraphQL?
Imagine you are building a social media application, and you have a REST API that allows users to retrieve their feeds of posts from their friends. You have a GET
endpoint as /feed
that returns a list of post objects, each with a message
, likes
, and comments
field.
With a REST API, you might retrieve the feed like this:
# GET /feed
[
{
"message": "Hello, world!",
"likes": 10,
"comments": [
{ "message": "Great post!" },
{ "message": "I agree!" }
]
},
{
"message": "I love GraphQL!",
"likes": 5,
"comments": [
{ "message": "Me too!" },
{ "message": "I'm learning it now." }
]
}
]
Imagine now that you want to add a new feature to your application that allows users to see a list of their own posts, along with the posts from their friends. With a REST API, you might need to add a new endpoint for this feature, such as GET /my_posts
, and modify the client to make a request to this new endpoint.
With GraphQL, you can add this new feature without having to add a new endpoint or modify the client. Instead, you can allow the client to specify which fields it wants in its query, and the server can return only the requested fields. For example, the client could request the message
and likes
fields for its own posts, and the message
, likes
, and comments
fields for the posts from its friends.
This allows you to add new features to your API more easily because you don’t have to worry about breaking existing clients or creating new endpoints for every new feature. It also allows the client to request only the data it needs, which can be more efficient than a REST API.