GraphQL

2022-12-11

After working with REST APIs for a while, I started exploring GraphQL. GraphQL is a query language for APIs, developed by Facebook. Instead of having multiple endpoints for different resources like REST, GraphQL has a single endpoint and the client decides exactly what data it wants.

The Problem with REST

In a REST API, each endpoint returns a fixed set of data. If we call /api/users/1, we get all the fields for that user. But what if we only need the name and email? We still get everything else, which wastes bandwidth. This is called over-fetching.

The opposite problem also exists. If we need the user's details and their recent orders, we have to make two separate requests: one to /api/users/1 and another to /api/users/1/orders. This is called under-fetching.

GraphQL solves both of these problems by letting the client specify exactly what it needs in a single request.

How It Works

In GraphQL, we define a schema on the server that describes all the types and their fields. For example:

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

type Order {
  id: ID
  item: String
  total: Float
}

The client sends a query specifying which fields it wants:

query {
  user(id: 1) {
    name
    email
    orders {
      item
      total
    }
  }
}

The server responds with exactly that structure. If we do not need the orders, we simply leave them out of the query and the server will not fetch them.

Mutations

To create, update, or delete data, GraphQL uses mutations. They work similarly to queries but are meant for write operations:

mutation {
  createOrder(userId: 1, item: "Keyboard", total: 85) {
    id
    item
  }
}

The mutation creates the order and returns the fields we specified.

When to Use GraphQL

GraphQL works well when the frontend needs flexibility in what data it fetches, or when there are multiple clients (web, mobile) that need different sets of data from the same API. It also reduces the number of network requests because we can get related data in a single query.

However, GraphQL is not always the better choice. For simple APIs with straightforward data needs, REST is simpler to set up and easier to cache. GraphQL also requires more work on the server side to define the schema and resolvers, and it can be more difficult to handle things like file uploads or caching compared to REST.

In some projects, I have seen teams use both. REST for simple CRUD operations and GraphQL for more complex data fetching scenarios where the client needs fine-grained control over the response shape.