Lesson 1 · Unit 04
GraphQL
A query with the shape of its answer, a schema of types, and one endpoint
What you practise
- The query has the shape of the answer, a schema of types, asking for exactly the fields needed, mutations, one endpoint
Try a question from this lesson
Pick one
A phone screen shows a user's name and the totals of their three latest orders. It calls two REST endpoints that return about 40 members each. What is wasteful?
GET /users/7 -> 40 members
GET /users/7/orders -> every order,
every memberCorrect answer
Two round trips, and mostly data the screen never shows
Why
The server chose the shape, so the client gets too much per call (over-fetching) and still needs several calls (under-fetching). On a slow mobile link both cost. GraphQL was designed for exactly this complaint.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Ask for the shape you want
A GraphQL query lists the fields the client wants, nested the way it wants them. The reply is JSON with the same shape, under "data", and nothing else.
One request can follow links between things: a user, then that user's orders.
{
user(id: "7") {
name
orders(last: 2) { total }
}
}
{"data": {"user": {
"name": "Ada",
"orders": [{"total": 1999},
{"total": 450}]
}}}Concept
The schema
The server publishes a schema: every type, its fields, and the type of each field. It is the contract, and tools can read it.
! means never null. [Order!]! is a list that is always present, holding orders that are never null. A field without !, such as email, may come back null.
Query is the entry point: the fields a query may start from.
type Query {
user(id: ID!): User
}
type User {
id: ID!
name: String!
email: String
orders(last: Int): [Order!]!
}
type Order {
id: ID!
total: Int!
}Concept
Mutations, and one endpoint
Reads are queries. Writes are mutations: named operations that change something and then return fields, like any query.
Both go to a single endpoint, usually as a POST. What happens is decided by the body, not by the method and the URL. So the HTTP method no longer tells anyone whether a request is safe to repeat.
POST /graphql
mutation {
cancelOrder(id: "41") {
id
status
}
}8 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× type the answer
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.