Software
100%

GraphQL vs REST: Solving Over-fetching and Under-fetching

How GraphQL optimizes data fetching in modern web applications compared to traditional REST API endpoints through client-driven queries.

Overview

GraphQL is an open-source data query and manipulation language for APIs, originally developed by Facebook. It provides a more efficient, powerful, and flexible alternative to the traditional REST (Representational State Transfer) architecture by exposing a single endpoint for all data interactions.

The Problem

In a REST API, data is organized around multiple "endpoints" (e.g., /users/1, /users/1/posts). This leads to two major issues in frontend development:

  • Over-fetching: A client hits /users/1 to get just the user's name, but the API returns the entire user object (email, address, phone number), wasting bandwidth.
  • Under-fetching (N+1 Problem): To display a user and their posts, the client must make one request to the user endpoint, wait for the response, and then make subsequent requests to the posts endpoint.

Solution and Configuration

GraphQL solves this by flipping the control. Instead of the server deciding what data to return based on the endpoint, the client explicitly asks for exactly what it needs.

Example Client Query:

query {
user(id: "1") {
name
posts {
title
}
}
}

The server will return a JSON object containing only the requested user's name and the titles of their posts in a single network request.

Technical Details

At the core of a GraphQL server is the Schema, which strongly types the data capabilities of the API. For every field in the schema, developers write a function called a Resolver. When a query is received, the GraphQL execution engine traverses the query and calls the corresponding resolvers to fetch data from databases or microservices. Because of its strongly typed nature, GraphQL enables incredible developer tooling, such as auto-generating API documentation and frontend code integration tools like Apollo Client.

Conclusion

While REST remains excellent for simple, resource-based architectures, GraphQL shines in complex applications with rich user interfaces (especially mobile apps on slow networks) where optimizing data payloads and minimizing round-trips are critical to performance.

Related Articles

View All