Software-Engineering

GraphQL

What is GraphQL?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It was developed by Facebook to solve the inefficiencies of REST APIs. Unlike REST, where you hit multiple endpoints to gather data, GraphQL allows you to access all your data through a single endpoint.

How it Works

GraphQL operates on a schema-first approach.

  1. Schema Definition: You define a strongly typed schema that describes all possible data and operations.
  2. Single Endpoint: The API exposes a single endpoint (usually /graphql) that accepts POST requests.
  3. Query Language: Clients send a query describing exactly the data structure they need.
    • Example Query:
      {
        user(id: "123") {
          name
          email
          posts {
            title
          }
        }
      }
      
  4. Resolvers: On the server, functions called “resolvers” are responsible for fetching the data for each field in the schema.

Why We Need It & When to Use

GraphQL was designed to solve the “over-fetching” and “under-fetching” problems common in REST.

Use GraphQL when:

Other Options

Pros and Cons

Pros

Cons