DEV Community

Pranav Bakare
Pranav Bakare

Posted on

REST API vs GraphQL | Best Explanation with example Analogy

Imagine you walk into a restaurant, and you have two ways to order food: the REST way and the GraphQL way.

REST API - The Fixed Menu

With REST, it’s like ordering from a set menu at a restaurant. Each item on the menu is predefined by the restaurant. If you want a burger, fries, and a drink, you have to order each item separately. Each endpoint in REST is like a menu item with a specific purpose, like /burger, /fries, /drink.

  1. Order Predefined Dishes: You ask the waiter (API) for a dish, and you get everything that comes with it. If you just want the burger bun, you still get the whole burger with patty, lettuce, tomato, etc. This can lead to over-fetching (getting more than you need).

  2. Separate Requests: To get everything you want, you might have to make multiple requests (one for each endpoint), which is time-consuming and can overload the network with extra requests.

  3. Limited Flexibility: If you want something custom, you’re often out of luck unless the menu (API) is updated to support that specific request.

GraphQL - The Custom Order

With GraphQL, it’s like talking to a personal chef. You describe exactly what you want, down to the specific ingredients and portions. You could ask for a burger with only the bun and patty, without extra items you don’t need.

  1. Customizable Orders: You can request only the data you need in a single query, avoiding over-fetching and under-fetching. For instance, if you want a burger with only the bun and patty, you can specify that, and you’ll only get those parts.

  2. Single Request: You can ask for everything you need in one go. For example, instead of separate requests for a burger, fries, and a drink, you can ask for all three at once, and the chef will prepare your custom order in one batch.

  3. Greater Flexibility: You can easily specify your custom needs without waiting for the menu (API) to be updated, making GraphQL more flexible and responsive to changing requirements.

Summary:

REST is like ordering off a fixed menu where you may get more or less than what you want and often need multiple requests to complete your meal.

GraphQL is like ordering from a personal chef who can customize exactly what you need in a single request, tailored to your specific requirements.

This is why GraphQL can be more efficient in scenarios where specific, diverse, or complex data requirements are needed.

Top comments (0)