GraphQL
medium 27 minGraphQL is a query language for APIs with a typed schema.
See it run
How a selection becomes an answer, and how the server keeps control of the work.
Operations
Answer one query
A phone asks for a name, three post titles and a points total.
Step 1 of 5
One request
One request
POST /graphql with the query and its variables. The gateway checks the token.
Step 1: One request
request = {"query": TEXT, "variables": {"id": "7"}}document = parse(request["query"])errors = validate(schema, document)if errors or cost(document) > LIMIT: return refuse(errors)data, errors = execute(document, variables, context)return {"data": data, "errors": errors}- Calls
- 1 request
- Guards against
- Round trips
- Fixed endpoints
- 3 requests
GraphQL does not store data. It is a typed layer in front of what you have.
In the real world
The same graphql doing real jobs. Pick one and step through it.
The points service fails while the phone asks for a whole screen.
Step 1 of 4
The service stops
One field will fail
The points service does not answer. User and posts are fine.
Step 1: The service stops
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A query in every resolver
criticalA page of 20 becomes 21 queries, and each nested list multiplies it.
Wrongauthor = lambda post: db.user(post.author_id)Rightauthor = lambda post: loaders.user.load(post.author_id)One loader for the whole server
criticalIts cache keeps old values, and gives one user what was loaded for another.
Wrongloaders = create_loaders() # at startRightdef context(request): return {"loaders": create_loaders()}Rate limit by requests only
majorOne request can ask for a million nodes.
Wrongallow(client, 1)Rightallow(client, cost(query))Access checks at the entrance only
criticalA private object can be reached through a comment, a list or a search.
Wrongif path == "me": check(user)Rightdef load_post(id, viewer): post = db.post(id) return post if may_see(viewer, post) else None
Interview tips
How to explain it
- A typed schema.
- The client selects fields.
- The answer has the same shape.
Say in an interview
- Loader per request.
- Pages, depth, cost.
- Authorize where you load.
Reach for it when
- Screens differ a lot.
- Round trips are slow.
- Several services feed one app.
Look elsewhere when
- Simple CRUD.
- Public cached reads.
- Files, or calls between services.