Example: Which is Better for APIs?
Let’s take the same pizza store example and understand how it works in GraphQL Query.
1. RESTful Approach
To order pizza in REST API approach, we may have to create two separate endpoints for pizzas and toppings. If you want a pizza with specific toppings, you have to make multiple requests.
Get Pizza Menu (GET /pizzas):
GET /pizzas
Server responds with a list of predefined pizzas and their toppings.
Select Pizza (GET /pizzas/{pizzaId}):
GET /pizzas/123
Fetch details for a specific pizza, but toppings are predefined and cannot be customized.
Place Order (POST /orders):
POST /orders
{
"pizzaId": 123,
"deliveryAddress": "123 GFG Office"
}
Place an order with a predefined pizza and toppings.
2. GraphQL Approach
With GraphQL, You have the option to order a pizza with your customization.
Write a Query:
query {
pizza(id: 123) {
size
crust
toppings {
name
}
}
}
Request the specific details you want for your pizza in a single query. A server-side query can be answered in a particular way with the use of arguments. It comes with a key:value pair and a field. It can either be a variable or a literal in the fields.
Get Custom Pizza:
{
"data": {
"pizza": {
"size": "Large",
"crust": "Thin",
"toppings": [
{"name": "Pepperoni"},
{"name": "Mushrooms"},
{"name": "Bell Peppers"}
]
}
}
}
Receive a custom-made pizza with the exact toppings you specified. Now you can order your customized pizza with your favourite toppings.
GraphQL vs REST: Which is Better for APIs?
In the world of web development, communication between a client (like a web or mobile app) and a server is crucial. Traditional REST APIs have been the go-to solution for many years, but GraphQL is emerging as a powerful alternative that offers more flexibility and efficiency. GraphQL is a query language for API and a server-side runtime engine used for data query and manipulation. It was developed by Facebook, and later made open source, and is now managed by GraphQL foundation hosted by Linux foundation. Many popular public APIs like Facebook, GitHub, Yelp, Shopify, and Google Directions API adopted GraphQL as the default way to access their services.