Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 37 ยท Getting Started

What Is GraphQL?

GraphQL is a query language for APIs where the client names exactly the fields it needs. Learn the problem it solves, its four parts and how a query runs.

GraphQL is a way for a client (a web page, a phone app, another server) to ask an API for data. The twist is who decides the shape of the answer. In a typical REST API the server decides: GET /books/1 returns whatever the server's developer put into a "book". In GraphQL the client writes down the exact fields it wants, and the server returns exactly those, in the same shape.

The name has two halves. "Graph" because your data is a web of connected things (an author has books, a book has reviews, a review has a reader). "QL" because it is a query language, a small text language for describing a slice of that web. GraphQL was created at Facebook to feed its mobile apps and was released as an open specification in 2015. It is a specification, not a product: many servers and clients, in many languages, implement it.

Nothing on this site can start a real GraphQL server, so every example here uses a stand-in: a few lines of JavaScript that behave like the real thing for the idea being taught. The lessons say each time what is real GraphQL and what is the stand-in. Real server code and tools appear in read-only blocks.

The problem: too much and too little

Imagine a book page that shows a title and the author's name. A REST endpoint such as /books/1 usually returns the whole book record, including fields this page never shows. That is over-fetching: wasted bytes, and on a slow mobile connection, wasted time.

The opposite problem is under-fetching. The book record only contains an authorId, so the page makes a second request to /authors/7. A screen that needs five related things can need five round trips, each waiting for the one before it.

Run this stand-in to see over-fetching with real numbers. The restBook function plays the part of a REST server.

JS Over-fetching in numbers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

One book is tiny. Multiply it by a list of 50 books on a phone, and the waste becomes visible. GraphQL attacks both problems with one idea: the client sends a description of the data it needs.

What a GraphQL request looks like

Here is a query. It is real GraphQL syntax, and you will learn every part of it in the next lessons:

GRAPHQL
{
  book(id: "b1") {
    title
    author {
      name
    }
  }
}

The server's answer is plain JSON that mirrors the query:

JSON
{
  "data": {
    "book": {
      "title": "The Dispossessed",
      "author": { "name": "Ursula K. Le Guin" }
    }
  }
}

Notice three things. The response has only title and author.name, nothing else. The author came back in the same request, because the query reached through the relationship. And the shape of the answer is the shape of the question, so a developer reading the query knows exactly what JSON will arrive.

The four parts of a GraphQL API

Four parts, four jobs

Schema Describes every type and field the API offers.
Query The client's request for specific fields.
Resolvers Functions that fetch the data for each field.
Server Receives queries, runs them, returns JSON.

The schema is the contract, the rest follows it.

1 / 3

Let us look at each part.

The schema is the contract. It lists the types that exist (Book, Author), the fields on each, and the entry points a client can start from. It is written in the Schema Definition Language (SDL). A tiny schema for our examples looks like this (read-only; you will write schemas in the SDL lesson):

GRAPHQL
type Query {
  book(id: ID!): Book
}

type Book {
  id: ID!
  title: String!
  year: Int
  author: Author!
}

type Author {
  id: ID!
  name: String!
}

The query is what the client sends. Before running anything, the server checks it against the schema. Ask for book { colour } and you get an error straight away, because Book has no colour field.

Resolvers are ordinary functions, one per field (or many fields sharing a default). A resolver for Query.book might look up a row in a database. A resolver for Book.author might fetch the author by the book's authorId. GraphQL itself does not know where data lives: that is entirely up to your resolvers. See Resolvers for the full story.

The server receives the request, parses the query, validates it against the schema, calls the resolvers for the requested fields, and assembles the JSON answer. In JavaScript this is often Apollo Server, GraphQL Yoga or graphql-js; in Python it can be Strawberry, Ariadne or Graphene. They all follow the same specification.

GraphQL is not a database, and it is not tied to one. Behind the resolvers there can be SQL, MongoDB, a REST API, a file, or a mix of all of them. GraphQL is the front door, not the storage.

How a request flows

sequenceDiagram
    participant C as Client
    participant S as GraphQL server
    participant R as Resolvers
    participant D as Data sources
    C->>S: POST /graphql (query)
    S->>S: Parse and validate against schema
    S->>R: Call resolver for each requested field
    R->>D: Read database, call services
    D-->>R: Rows and objects
    R-->>S: Field values
    S-->>C: JSON with data (and errors, if any)

One request goes in, one JSON document comes out, however many data sources were touched.

A runnable stand-in: executing a query over an object

The next stand-in is a miniature "server". It holds a plain JavaScript object as its data, and the "query" is a nested JavaScript object saying which fields to keep (true means "this field"; an object means "go inside"). The real GraphQL query is text and gets parsed first; you will build that parsing step in Your First Query. The core idea, walk the selection and copy only what was asked for, is the same.

JS A tiny query executor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same data object answers three differently shaped questions. That is GraphQL's central promise, in about ten lines. What the real thing adds on top is a type system, validation, a text syntax, resolvers instead of plain properties, and error handling.

When GraphQL shines

GraphQL pays off when many different clients need different slices of the same data (a web app, an iOS app, a smart-TV app), when screens combine data from several backend services, and when front-end and back-end teams want to move without constant negotiation about endpoints. It is less compelling for a tiny API with two endpoints and one client, or for simple file downloads. GraphQL vs REST compares the trade-offs honestly.

Disadvantages to plan for

  • Caching is harder. Most queries are POST requests to one URL, so the plain HTTP caches in browsers and CDNs do not help by default. See Caching and Performance.
  • Expensive queries. A client can ask for deeply nested or huge lists. You need depth, complexity and rate limits (Query Limits and Security).
  • N+1 database access. Resolvers run per field, which can fire one query per row unless you batch (N+1 and DataLoader).
  • A learning curve and more tooling. You need a schema, resolvers and often a client library, which is overkill for a small API.
  • Uploads and errors need conventions. File uploads are not part of the core spec, and errors arrive as HTTP 200 with an errors list, so monitoring must look inside the body.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who decides which fields appear in a GraphQL response?

    The client lists the exact fields it wants, and the server returns only those, in the same shape as the query.
  2. 2. Which problem is described by needing several round trips to assemble one screen?

    Under-fetching means one response does not contain enough, so the client has to make more requests. Over-fetching is the opposite: receiving more than is needed.
  3. 3. What is the job of a resolver?

    Resolvers are functions that produce field values. They may read a database, call another service or just return a property.
  4. 4. Is GraphQL a database?

    GraphQL is a specification for APIs. The data can live in SQL, NoSQL, files or other services, reached through resolvers.

Summary

  • GraphQL lets the client describe the exact data it needs, and the response mirrors that description.
  • It reduces over-fetching (extra fields) and under-fetching (extra round trips).
  • The four parts: schema (the contract), query (the request), resolvers (field functions) and the server that ties them together.
  • Typically one endpoint (POST /graphql) serves every query.
  • It is a specification, independent of any database or language.
  • The stand-ins in this tutorial are small JavaScript or Python programs that show the mechanics; real servers are shown read-only.

Next: GraphQL vs REST