Frontend Patterns

Pattern

GraphQL Query

Request precisely the data needed using GraphQL's declarative query language.

GraphQL Query

Problem

REST endpoints return massive payloads with unnecessary nested data, forcing clients to download hundreds of fields when only a few are needed. Components requiring different data combinations force developers to create numerous custom endpoints or accept over-fetching. Mobile users waste bandwidth downloading unused data, and backend teams struggle to maintain endpoint explosion.

Solution

Request exactly the data you need by declaring fields in a strongly-typed query language. This reduces over-fetching and under-fetching compared to REST while providing schema validation.

Example

This example demonstrates a GraphQL query that requests specific fields from a user, including nested post titles, avoiding over-fetching unnecessary data.

# Query definition with required ID parameter
query GetUser($id: ID!) {
  user(id: $id) {
    # Request only the fields needed
    name
    email
    # Nested query for related data
    posts {
      title    # Only fetch post titles, not full post objects
    }
  }
}

Benefits

  • Eliminates over-fetching by allowing clients to request only the fields they need.
  • Reduces the need for multiple endpoints since one query can fetch related data.
  • Provides strong typing and validation through the GraphQL schema.
  • Improves performance for mobile users by minimizing data transfer.

Tradeoffs

  • Requires learning GraphQL syntax and concepts beyond simple REST endpoints.
  • Adds complexity with query optimization, caching, and N+1 query problems.
  • Needs a GraphQL server implementation which can be complex to set up.
  • Makes debugging harder when queries are dynamically generated or deeply nested.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.