Skip to main content
GraphQL Basics
CHAPTER 03 Beginner

GraphQL vs REST APIs

Updated: May 13, 2026
15 min read

# CHAPTER 3

GraphQL vs REST APIs

1. Introduction

For the last decade, REST (Representational State Transfer) has been the undisputed king of API architectures. However, as applications became more complex, particularly on mobile networks, developers started running into significant limitations with REST. In this chapter, we will directly compare GraphQL and REST. We will explore the concepts of over-fetching and under-fetching, examine flexible queries, and provide side-by-side examples to demonstrate why many developers are choosing GraphQL for modern applications.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Identify the core limitations of traditional REST APIs.
  • Define and explain "Over-fetching" and "Under-fetching."
  • Compare how endpoints are structured in REST vs. GraphQL.
  • Understand how GraphQL provides flexible, client-driven queries.
  • Decide when to use REST and when to use GraphQL.

3. Beginner-Friendly Explanation

Imagine you are packing for a weekend trip. Using a REST API is like buying pre-packed suitcases. Suitcase A has clothes, Suitcase B has toiletries. If you only need a toothbrush from Suitcase B, you still have to take the whole heavy suitcase. You got more than you needed (Over-fetching). If Suitcase A doesn't have socks, you have to go buy a third suitcase just for socks. You didn't get enough (Under-fetching).

Using GraphQL is like packing your own bag. You look at a master list of items (the Schema) and say, "I want two shirts, one toothbrush, and socks." The server packs exactly those items into a single bag and hands it to you. It is perfectly tailored to your needs.

4. Real-World Examples

  • The Blog Scenario (REST): To display a blog post with its author's name and top 3 comments, a client might have to make 3 separate HTTP requests:
  1. 1. /posts/1 (Gets the post)
  1. 2. /users/42 (Gets the author details)
  1. 3. /posts/1/comments (Gets all comments)
  • The Blog Scenario (GraphQL): The client makes exactly 1 HTTP request to /graphql, asking specifically for the post content, the author's name, and the first 3 comments.

5. Detailed Code Examples

Let's look at how data fetching differs in code.

REST Example (PHP / cURL making multiple requests):

php
123456
<?php
// Request 1: Get user
$user = file_get_contents(&#039;https://api.example.com/users/1');
// Request 2: Get user's posts
$posts = file_get_contents(&#039;https://api.example.com/users/1/posts');
?>

GraphQL Example (PHP making a single request):

php
1234567891011121314151617181920212223
<?php
$query = json_encode([
    &#039;query' => '
        query {
            user(id: 1) {
                name
                posts {
                    title
                }
            }
        }
    &#039;
]);

// Single request fetches everything perfectly formatted
$response = file_get_contents(&#039;https://api.example.com/graphql', false, stream_context_create([
    &#039;http' => [
        &#039;method' => 'POST',
        &#039;header' => 'Content-Type: application/json',
        &#039;content' => $query
    ]
]));
?>

6. Query Examples (GraphQL's Solution)

Here is how elegantly GraphQL solves the multi-request problem.
graphql
12345678910
query {
  author(id: "5") {
    name
    email
    recentPosts(limit: 2) {
      title
      date
    }
  }
}

7. Mutation Examples

In REST, updating data uses different HTTP methods (PUT, PATCH, DELETE) on different URLs (/users/1). In GraphQL, it all goes to the same endpoint using a Mutation.
graphql
123456
mutation {
  updateUserEmail(id: "5", newEmail: "new@example.com") {
    id
    email
  }
}

8. Schema Examples

The schema defines the relationship, allowing GraphQL to traverse connections seamlessly.
graphql
12345678910
type Author {
  id: ID!
  name: String
  recentPosts: [Post]
}

type Post {
  title: String
  date: String
}

9. Best Practices

  • Don't abandon REST completely: REST is still excellent for simple APIs, file uploads, and microservice-to-microservice communication. Choose the right tool for the job.
  • Use GraphQL for Data-Heavy UIs: If you are building a complex React, Vue, or mobile application with diverse data needs, GraphQL is vastly superior.
  • Monitor Payload Size: While GraphQL prevents over-fetching fields, clients can accidentally ask for deeply nested lists (e.g., users -> friends -> friends -> friends), causing server strain.

10. Common Mistakes

  • Assuming GraphQL is universally faster: GraphQL reduces network requests, which helps on mobile connections, but calculating complex queries on the server requires processing power. Badly written GraphQL can actually be slower.
  • Duplicating logic: Don't put business logic inside your GraphQL layer. It should merely route the request to your existing backend PHP services.

11. Mini Exercises

  1. 1. Define Over-fetching in one sentence.
  1. 2. Define Under-fetching in one sentence.
  1. 3. Compare the number of URLs (endpoints) used in a typical REST API versus a typical GraphQL API.

12. Coding Challenges

Challenge 1: You are building an app that shows a list of movies. You only need the title and rating.
  • How would a REST API respond to /movies?
  • Write the GraphQL query to fetch exactly what you need.

13. MCQs with Answers

Question 1

What is "Over-fetching"?

Question 2

How does GraphQL typically handle endpoints?

Question 3

If a client needs a user's data AND that user's latest orders, how many requests are typically made in REST vs GraphQL?

14. Interview Questions

  • Q: Compare and contrast GraphQL and REST. What problem does GraphQL solve?
  • Q: Explain "N+1 Problem" in the context of APIs (Under-fetching).
  • Q: In what scenario would you choose REST over GraphQL?

15. FAQs

Q: Can I use REST and GraphQL in the same project? A: Absolutely! Many companies wrap their existing legacy REST APIs inside a new GraphQL server. This allows frontend developers to enjoy GraphQL while the backend slowly transitions.

Q: Is GraphQL harder to cache than REST? A: Yes. Because REST uses unique URLs for every resource, standard HTTP caching (like Varnish or CDN) works perfectly. Since GraphQL uses a single endpoint with dynamic POST bodies, standard HTTP caching is much more difficult, requiring specialized clients like Apollo.

16. Summary

In this chapter, we compared GraphQL directly against REST. We learned that REST's fixed data structures lead to over-fetching (getting unused data) and under-fetching (requiring multiple round-trip requests). GraphQL solves this by providing a single endpoint where the client dictates exactly the shape and amount of data it requires, resulting in highly efficient, flexible, and fast client applications.

17. Next Chapter Recommendation

Now that you understand the "why" of GraphQL, it is time to get our hands dirty. Proceed to Chapter 4: Setting Up a GraphQL Environment to install the necessary tools, set up a GraphQL Playground, and prepare a PHP environment to run our very first GraphQL server.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·