What is GraphQL
A bookshop app needs a book's title, its author's name and its three newest review ratings, and nothing else. With GraphQL the app writes that wish down as a query, sends it to the server, and gets back JSON in exactly that shape. This whole course works on that one bookshop API.
The rule
Describe the shape you want; the server fills it in.
GraphQL is a query language for APIs plus a set of rules a server follows to answer it. It has three parts that always travel together:
- A schema: the server's typed menu of everything a client may ask for.
- Operations: a query to read, a mutation to change, a subscription to listen.
- Resolvers: server functions that fetch the value for each field.
Here is part of the bookshop schema, written in GraphQL's schema language:
type Query {
book(id: ID!): Book
}
type Book {
id: ID!
title: String!
price: Float!
author: Author!
}
type Author {
id: ID!
name: String!
}A client asks for a book and picks its fields:
query {
book(id: "b1") {
title
author { name }
}
}The answer mirrors the question:
{ "data": { "book": { "title": "The Salt Road", "author": { "name": "Mira Kapoor" } } } }GraphQL began inside Facebook in 2012, was published as an open specification in 2015, and is now looked after by the GraphQL Foundation. It is a specification, not a product: many servers in many languages implement it. It also says nothing about which database you use. Your data can live in PostgreSQL, another service or a file; resolvers hide that.
The shortcut
To read any GraphQL exchange, lay the query over the response. Every field name in the query becomes a key in the JSON, at the same depth, under a top-level data key.
Find the root field
The query starts at
book(id: "b1"), so the JSON hasdata.book.
A common slip is to think GraphQL is a database query language like SQL. It is not: it talks to an API, and the server decides how each field is fetched.
Drills
Answer fast — trust the rule.
What does a GraphQL response contain?
Which part of a GraphQL API lists the types and fields a client may ask for?
A query selects book { title author { name } }. Which key is NOT in the response?
Which statement about GraphQL is true?
Remember
- Describe the shape you want; the server fills it in, under
data. - Shortcut: lay the query over the response; keys match fields at the same depth.
- Trap: GraphQL is an API language, not a database query language.
