What Is GraphQL?

GraphQL is a query language for APIs, paired with a server-side runtime that executes queries based on a type system you define. Released as open-source in 2015 by Facebook, it works with various programming languages and databases, offering flexibility for developers.

Unlike REST APIs, which use multiple endpoints for different data, GraphQL uses a single endpoint (e.g., /graphql) to handle all requests. This makes APIs more efficient and easier to use.

How Does GraphQL Work?

In a typical REST API, you might interact with endpoints like:

  • GET /books to fetch all books.
  • GET /books/:id to fetch a single book by ID.

This approach has two common issues:

  • Over-fetching: You get more data than needed (e.g., book title, author, genre, when you only want title and author). more data than you need.
  • Under-fetching: You need multiple requests to gather related data.

GraphQL solves this by letting you request exactly the data you need in a single query.

Example:

query {
  books {
    title
    author
  }
}

Response:

{
  "data": {
    "books": [
      { "title": "1984", "author": "George Orwell" },
      { "title": "To Kill a Mockingbird", "author": "Harper Lee" }
    ]
  }
}

This query fetches only the book titles and authors, avoiding unnecessary data.

Key Features of GraphQL

1. Get Exactly What You Need

GraphQL queries mirror the structure of your desired data. You define types and fields in your API, and the GraphQL service ensures queries are valid before executing them. For instance, querying user information could look like this.

Example:

query {
  me {
    name
  }
}

Response:

{
  "data": {
    "me": { "name": "Mostafa YazdaniFard" }
  }
}

2. Evolve APIs Without Versioning

GraphQL lets you update your API without breaking existing clients. You can add new fields or deprecate old ones.

Example:

type User {
  fullName: String
  nickname: String
  name: String @deprecated(reason: "Use `fullName` instead.")
}

Clients can transition to new fields gradually.

3. Single Endpoint

All queries go through one endpoint (e.g., /graphql), simplifying API management compared to REST’s multiple endpoints.

4. Flexible Data Sources

GraphQL isn’t tied to a specific database. You write resolver functions to fetch data from any source (databases, APIs, etc.).

Example Resolver (in Python):

## Python
def resolve_user_name(user, info):
    # Extract user ID from the user object
    user_id = user.id

    # Access the database from the context
    db = info.context.db

    # Get the user's full name from the database
    full_name = db.get_user_full_name(user_id)

    return full_name

GraphQL vs. REST API

The table above shows a quick overview of the differences between REST API and GraphQL.

API TypeProsCons
REST API– Multiple endpoints clearly separate resources
– Supports structured versioning
– Over-fetching or under-fetching of data
– Requires multiple requests
– Needs new versions when changes occur
GraphQL
– Fetches only the required data
– Single endpoint (/graphql)
– No versioning required
– Efficient single query
– Single endpoint can reduce clarity of resource separation
– Query design must be handled carefully

Try GraphQL Yourself

Experiment with GraphQL using tools like Apollo Explorer. Here’s a simple query to try:

query {
  hero {
    name
    id
  }
}

Expected Response:

{
  "data": {
    "hero": { "name": "R2-D2", "id": "2001" }
  }
}

Next Steps

You now understand GraphQL’s basics! In Part 2, we’ll explore Schemas and Types to help you design your own GraphQL API.

Categorized in: