GraphQL Intro
GraphQL is a query language for APIs and a runtime that answers those queries. Instead of a server deciding what each URL returns, the client describes the exact shape of the data it wants, and the server replies with JSON in that same shape.
It was created at Facebook in 2012 to feed its mobile apps, open-sourced in 2015, and is now maintained by the GraphQL Foundation. GitHub, Shopify, Netflix and many others expose GraphQL APIs.
A first taste
Here is a complete GraphQL "server" in a few lines of JavaScript. The schema says what can be asked, the root value says how to answer, and graphql() executes a query. Press ▶ Run:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query {
greeting: String
luckyNumber: Int
}
`);
const rootValue = {
greeting: () => 'Hello, GraphQL!',
luckyNumber: () => 7,
};
const result = await graphql({ schema, source: '{ greeting }', rootValue });
console.log(JSON.stringify(result, null, 2));{
"data": {
"greeting": "Hello, GraphQL!"
}
}
The query asked only for greeting, so the answer contains only greeting, even though luckyNumber exists. Change the query to { greeting luckyNumber } and run again.
Why not just REST?
In a REST API every resource has its own URL, and the server fixes what each endpoint returns:
GET /users/42 -> { id, name, email, address, createdAt, ... }
GET /users/42/posts -> [ { id, title, body, tags, ... }, ... ]
GET /posts/7/comments -> [ ... ]A profile screen that needs "the user's name and the titles of their last three posts" has two problems:
| Problem | What happens in REST | What GraphQL does |
|---|---|---|
| Over-fetching | /users/42 sends email, address, … that the screen never shows |
You list only the fields you need |
| Under-fetching | You need a second request for the posts (and maybe a third) | One query can follow relationships |
| Versioning | New shapes often mean /v2/... endpoints |
Add fields; old clients simply don't ask for them |
| Documentation | Kept separately, can drift | The schema is the contract and can be introspected |
The same screen in GraphQL is a single request to a single endpoint (usually POST /graphql):
{
user(id: 42) {
name
posts(last: 3) {
title
}
}
}Following relationships in one query
Let's make that work. Objects can contain other objects, and the query walks through them:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Post { title: String }
type User { name: String, email: String, posts: [Post] }
type Query { user(id: Int): User }
`);
const users = {
42: {
name: 'Ada',
email: 'ada@example.com',
posts: [{ title: 'Notes on the Engine' }, { title: 'Poetical Science' }],
},
};
const rootValue = { user: ({ id }) => users[id] };
const query = `{
user(id: 42) {
name
posts { title }
}
}`;
const result = await graphql({ schema, source: query, rootValue });
console.log(JSON.stringify(result, null, 2));{
"data": {
"user": {
"name": "Ada",
"posts": [
{
"title": "Notes on the Engine"
},
{
"title": "Poetical Science"
}
]
}
}
}
Notice that email is not in the result: the client didn't ask for it.
What GraphQL is not
- Not a database. GraphQL sits in front of whatever you have: SQL, MongoDB, other REST APIs, files. Your code decides how each field is fetched.
- Not tied to a language. There are servers for JavaScript, Java, Python, Go, Rust, C#, and more. This course uses graphql-js, the reference implementation, because it runs right here in the browser.
- Not always better than REST. Simple CRUD APIs, file downloads and heavily cached public data are often easier with REST. GraphQL shines when many clients need different views of connected data.
The three operation types
| Operation | Purpose | Example |
|---|---|---|
query |
Read data | query { user(id: 1) { name } } |
mutation |
Change data | mutation { addPost(title: "Hi") { id } } |
subscription |
Receive a stream of updates | subscription { newMessage { text } } |
You'll meet all three in this course.
Note: In the playgrounds we call
graphql()directly, without any HTTP. That is exactly what a real server does internally after it receives a request, so everything you learn transfers. The "Serving over HTTP" lesson shows the network part.
Test yourself
Who decides which fields appear in a GraphQL response?
- The server, per endpoint
- The client, in its query
- The database schema
- The HTTP method
Receiving fields you don't need from a REST endpoint is called…
- Under-fetching
- Over-fetching
- Batching
- Introspection
Which operation type is used to change data?
- query
- subscription
- mutation
- fragment