Dung (Donny) Nguyen

Senior Software Engineer

What is GraphQL?

GraphQL is an open-source query language and runtime developed by Facebook in 2012 and released publicly in 2015. It is designed for APIs, enabling clients to request only the data they need and nothing more. GraphQL provides a more flexible and efficient alternative to traditional REST APIs by offering a single endpoint and a well-defined schema for interacting with data.

At its core, GraphQL allows clients to:


Key Features of GraphQL

  1. Flexible Queries: Clients define the structure of the response, requesting only the fields they need.
  2. Single Endpoint: GraphQL operates with a single endpoint, /graphql, for all queries and mutations.
  3. Real-Time Updates: GraphQL supports real-time capabilities through subscriptions.
  4. Strongly-Typed Schema: Every GraphQL API is backed by a schema, which serves as a contract between client and server.
  5. Tooling and Introspection: Built-in introspection capabilities allow clients to explore the schema dynamically.

Differences Between GraphQL and REST

Feature GraphQL REST
Data Fetching Clients request only the data they need. Servers define the response structure; often over-fetch or under-fetch data.
Endpoints Single endpoint (/graphql) for all operations. Multiple endpoints (/users, /posts, etc.) for different resources.
Schema Uses a strongly-typed schema with types for queries, mutations, and subscriptions. Typically lacks a unified schema, relying on documentation.
Nested/Related Data Supports nested queries to fetch related data in one request. Requires multiple requests or custom endpoints for nested data.
Real-Time Updates Supports real-time updates via subscriptions. Requires additional protocols (e.g., WebSockets) or polling.
Versioning No versioning needed; schema evolves with deprecation notices. Uses versioned endpoints (e.g., /v1/users) for changes.
Performance Fewer network requests due to single query for related data. May result in more requests or larger payloads.
Tooling & Introspection Built-in introspection allows tools like GraphiQL to explore APIs. Introspection is typically not available.

Example Comparison

REST API Example

Endpoint: /user/1
Response:

{
  "id": 1,
  "name": "Alice",
  "posts": [1, 2]
}

For post details, you make another request to /posts for each post.


GraphQL API Example

Query:

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

Response:

{
  "data": {
    "user": {
      "name": "Alice",
      "posts": [
        { "title": "First Post", "content": "Hello World!" },
        { "title": "Second Post", "content": "GraphQL is awesome!" }
      ]
    }
  }
}

Here, all the required data is fetched in a single request, reducing the number of network calls and payload size.

In summary, GraphQL offers a client-driven, flexible approach to data fetching compared to REST’s server-driven, endpoint-based architecture.