GraphQL Overview

Learn what GraphQL is and how it helps you ship features faster


Learn how GraphQL provides an efficient and flexible way to organize and interact with your data and what to consider when adopting it.

Why adopt GraphQL?

Managing data in modern applications is challenging. Most applications require:

  • Distinct frontend clients for multiple platforms (web, iOS, etc.), each with different data requirements

  • A backend that serves data to clients from multiple sources (Postgres, Redis, etc.)

  • State and cache management for both the frontend and the backend

GraphQL can help simplify some of the complexities these requirements create.

Consistent APIs for clients

GraphQL's declarative model and strongly typed schemas help you create a consistent, predictable API for all your clients. As you add, remove, and migrate data sources, the API doesn't change from the client's perspective.

Enhanced developer experience

One of GraphQL's greatest strengths is the developer experience it enables. Thanks to GraphQL's strong typing and built-in support for introspection, developer tools for GraphQL are extremely powerful. These tools let you do things like:

  • Explore the full structure of a schema, complete with docstrings

  • Compose new operations with live validation and autocomplete

  • Register your schema with a management service that tracks and checks changes

These tools and capabilities accelerate feature design, development, and deployment for everyone, from solo developers to global enterprises.

What is GraphQL?

GraphQL is an open-source query language and specification for APIs that lets clients request exactly the data they need. For example, the following GraphQL query lets clients specify the exact fields they need from the user type:

GraphQL
query UserOrders {
  user(id: "123") {
    id
    name
    email
    orders {
      orderId
      totalAmount
      items {
        productId
        productName
        quantity
      }
      orderDate
    }
  }
}
note
Querying a GraphQL API doesn't only refer to fetching data from it. "Querying" also includes updating data through an operation type called mutations.
Learn more about common GraphQL misconceptions.

The previous query also shows how clients can interact with multiple data types in one request, such as retrieving a user's orders and that order's products. In a traditional REST API, multiple endpoints would be required to fetch different resources ( /user, /user/orders). Multiple dependent network requests can result in slower page loads and additional battery consumption on mobile devices. This logic is also difficult to reuse on other pages that display slightly different data.

Industry leaders don't see GraphQL as a replacement for REST, though. Instead, they use it as a composition layer on top of existing APIs, providing a unified interface for clients to access different data sources.

Learn more about how REST and GraphQL can work together.

Who is GraphQL for?

GraphQL benefits various roles across your organization in different ways.

Role GraphQL Benefits Commonly Used Tools

Frontend Developers

Frontend developers appreciate GraphQL's ability to fetch the necessary data in a single client-side query, reducing multiple API calls. This flexibility allows for the creation of rich, dynamic UIs with faster load times. GraphQL's declarative nature enables easy adaptation of UI components to new data without backend changes.Apollo Client, Apollo iOS, Apollo Kotlin, Apollo GraphOS

Backend Developers

GraphQL provides a powerful layer to unify data from various backend sources, including databases, REST APIs, and microservices, into a single, consistent API. It enables the creation of flexible APIs that can evolve with changing client applications.Apollo Server, Rover CLI, Apollo GraphOS

Architects

GraphQL's composition layer simplifies API platform architecture by producing a single endpoint from multiple data sources. GraphQL's strongly typed schemas enforce a contract between clients and servers, helping manage API evolution safely.Apollo GraphOS, Rover CLI, GraphOS Router

Platform Teams

Platform teams use GraphQL to establish a central data layer for organizations. Tools can analyze the centrally collected operation data to help monitor API performance, track schema changes, and ensure data consistency across teams, fostering collaboration and accelerating feature delivery.Apollo GraphOS, Rover CLI, GraphOS Router

How does GraphQL work?

GraphQL schemas are the blueprints for your GraphQL API. Schemas define the structure and relationships in your data. They serve as a contract between clients and servers, ensuring that both parties agree on the shape and structure of the data. Schemas include data types and the operations clients can perform on that data—specifically, queries, mutations, and subscriptions.

Types

Types define the data structure that clients can query in your GraphQL API. Each type represents a different object in your application, such as Product, User, or Order.

For example, an e-commerce application might include the following types:

  • Product: Represents an individual product with fields like id, name, description, price, and inStock.

  • User: Represents a user with fields like id, name, email, and a list of orders.

  • Order: Represents an order with fields like id, a list of products, the total cost, the time it was placedAt, and its current status.

Here's how these types look in a GraphQL schema:

GraphQL
type Product {
  id: ID!
  name: String!
  description: String
  price: Float!
  inStock: Boolean!
}

type User {
  id: ID!
  name: String!
  email: String!
  orders: [Order!]!
}

type Order {
  id: ID!
  products: [Product!]!
  total: Float!
  placedAt: DateTime!
  status: String!
}

These types are the backbone of your GraphQL schema, defining the data that clients can query, mutate, and subscribe to.

Queries

Queries fetch data from your GraphQL API. They are analogous to GET requests in REST. A query specifies the shape and structure of the data to retrieve. For example:

GraphQL
query {
  products {
    name
    price
  }
}

Mutations

Mutations modify data on the server. They are analogous to POST, PUT, PATCH, or DELETE requests in REST. A mutation specifies the changes to make, for example:

GraphQL
mutation {
  addProduct(name: "New Product", price: 19.99) {
    id
    name
    price
  }
}

Subscriptions

Subscriptions are used to listen for real-time updates from your GraphQL API. They enable real-time communication by allowing clients to receive data updates when specific events or changes occur. This example subscription listens for updates about newly added products:

GraphQL
subscription {
  productAdded {
    id
    name
    price
  }
}

GraphQL considerations

When deciding whether to adopt a technology, it's just as important to understand the technology's limitations as it is to understand its benefits. Consider the following when using GraphQL:

Performance

Your GraphQL schema defines which types and fields your clients can query. Your GraphQL server's resolvers define how those types and fields are populated from your data sources.

Depending on your schema and resolver definitions, your server might inadvertently support resource-intensive operations. Nested queries can trigger multiple database trips (the N+1 problem), and clients can request overly complex or deeply nested queries.

GraphQL best practices

It's important to design your schema to support the operations your clients need without supporting unnecessary operations that affect performance. You can mitigate the N+1 problem by using data loaders. Setting up trace reporting can help identify and improve slow operations. Finally, techniques like request limits and demand control can protect your graph from high-cost operations.

Caching

Web browsers use HTTP caching to fetch data according to its URL. With GraphQL, you fetch all data from the same URL—the URL of your GraphQL server or router. Consequently, you can't rely on the cached value for this URL.

GraphQL best practices

Apollo Client provides powerful client-side caching features, though these features often require some configuration to maximize their effectiveness. Server-side caching can be done at the resolver level to cache individual data fetches. Finally, caching strategies like persisted queries and entity caching can help optimize repeated query performance.

Security

GraphQL APIs are broadly open by design. They let client applications send queries with arbitrary shapes and sizes. While this allows for expedited client development and a highly performant API platform, it necessitates securing your graph against potentially malicious requests.

GraphQL best practices

It's best to use a defense-in-depth strategy via features like authorization and safelisting with persisted queries, which also helps with performance. Additionally, following best practices like turning off introspection in production can help keep your graph safe.

Change management

GraphQL introduces a new conceptual model for representing and interacting with data. An organization that's comfortable with this model can design, implement, and ship features quickly. However, the process of becoming comfortable with this model can take time.

  • Frontend developers must come up to speed with a new API for fetching and manipulating data.

  • Backend developers must come up to speed with how to handling incoming requests from the frontend.

  • Developers across the organization must collaborate on a single, product-driven GraphQL schema and appoint individuals as its official maintainers.

GraphQL best practices

It pays to invest in effective onboarding and proper schema design from the start. The Apollo docs, blog, and community forum are all here to help your organization adopt GraphQL and take full advantage of it.

Learn more

Apollo offers the following resources depending on your familiarity with GraphQL and your preferred learning modes:

Feedback

Forums