Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
REST, RPC, GraphQL, gRPC and streaming: what each is for.
When is a request best described as an operation on a resource?
REST gives resources addresses and uses HTTP methods to describe work with them. RPC names a procedure, which can make a domain operation easier to express.
A client needs the current job snapshot
Request the job resource by its ID
The response carries the current representation
A client needs the current job snapshot
Request the job resource by its ID
The response carries the current representation
Given A client needs the current job snapshot and The response carries the current representation, write down the missing step that connects them.
Request the job resource by its ID
Now take Request the job resource by its ID and the result above. Write an input and an implementation that could produce this trace.
A client needs the current job snapshot. Check that your implementation produces the result shown above.
A client needs to see each model token as it arrives. What kind of exchange fits?
Use a streaming response. The client can act on partial output before the server completes the generation.
Check this when debugging. Calling any JSON-over-HTTP API REST, even one URL that takes an action name.
"API" covers several quite different designs, the way "restaurant" covers both a buffet and a set menu. The Claude Messages API is REST-style JSON over HTTP, and it streams with server-sent events. MCP uses JSON-RPC. Payment providers send webhooks. Knowing the styles lets you read any API's documentation quickly, and pick the right one for the thing you build. Most AI products lean on the last one in this lesson, a stream, because a model's reply takes seconds and users want the first words at once.
GET /orders/88
REST names things with nouns (/orders/88) and uses HTTP's verbs for actions: GET reads, POST creates, DELETE removes. RPC-style APIs name the action instead, and this lesson compares the styles.
This rests on HTTP from the wire up: every style here travels in the same request line, headers and body. The styles differ in what goes in the request line and what goes in the body. Take one question, "give me campaign cmp_103's name and spend", and ask it three ways.
REST organizes an API like a library. The things in your system, such as campaigns and orders, are its resources, the nouns, and each has an address. The HTTP methods are the verbs:
| action | method and path | success status |
|---|---|---|
| list campaigns | GET /campaigns | 200 |
| read one | GET /campaigns/cmp_103 | 200 |
| create one | POST /campaigns | 201 |
| replace one | PUT /campaigns/cmp_103 | 200 |
| change some fields | PATCH /campaigns/cmp_103 | 200 |
| delete one | DELETE /campaigns/cmp_103 | 204 (no body) |
Each request stands alone and carries everything the server needs, which is called being stateless. GET never changes anything, because browsers, caches and link-preview bots repeat it freely.
POST /api with the body {"action": "delete_user", "id": 7}. Which style is it?RPC: the action's name is in the body
The action's name travels in the body and one URL serves everything, which is RPC, whatever the docs call it. That is not wrong, but it means REST's rules about caching and safe methods don't apply.
RPC (remote procedure call) names the action: pause_campaign, tools/call. To you it looks like calling a function that runs on another computer. JSON-RPC sends {"jsonrpc": "2.0", "method": ..., "params": ..., "id": ...} to one URL; MCP is built on it, and JSON-RPC 2.0 in depth covers it in full. gRPC describes each function in a .proto file and sends compact binary messages over HTTP/2, which suits services inside one company.
GraphQL has one endpoint. The client sends a query naming the exact fields it wants and gets back JSON of that shape, which avoids over-fetching (a phone screen receiving 40 fields it ignores) and under-fetching (three calls to fill one page). The cost moves to the server, which must limit how deep and how expensive a query can be.
raw = (
"POST /v1/campaigns HTTP/1.1\r\nHost: api.gradient.test\r\n"
"Content-Type: application/json\r\n\r\n{\"name\": \"Spring\"}"
)
head, body = raw.split("\r\n\r\n")
request_line, *headers = head.split("\r\n")
print(request_line.split(" ")[0], len(headers), body)POST 2 {"name": "Spring"}
The blank line splits the head from the body. The head's first line is the request line, and the two lines after it are headers. Every style in this lesson uses this envelope.
Polling asked twice for nothing. The webhook arrived once, with the news.
Write a sentence or two, then compare it with a good answer in the lesson.
The three requests for one campaign, as data. All three travel over the same HTTP.
Fetching one campaign's name and spend, shown as the request each style sends.
import json rest = ("GET", "/v1/campaigns/cmp_103", None) json_rpc = ("POST", "/rpc", { "jsonrpc": "2.0", "id": 1, "method": "get_campaign", "params": {"id": "cmp_103"}, }) graphql = ("POST", "/graphql", { "query": 'query { campaign(id: "cmp_103") { name spend } }', }) for name, (method, path, body) in [ ("REST", rest), ("JSON-RPC", json_rpc), ("GraphQL", graphql), ]: print(f"{name:9} {method:4} {path:22} {json.dumps(body) if body else ''}")
REST puts the "what" in the URL and the method. JSON-RPC puts it in the body as a function name. GraphQL puts a whole query in the body, including which fields to return.
A price list on a phone needs two fields per product. A REST record carries them all; a GraphQL query returns only the two.
import json products = [{"id": n, "name": f"Tent {n}", "price": 89.0, "stock": 14, "description": "A roomy two-person tent. " * 10, "reviews": list(range(20))} for n in range(20)] rest = json.dumps(products) graphql = json.dumps([{"name": p["name"], "price": p["price"]} for p in products]) print("REST bytes:", len(rest)) print("GraphQL bytes:", len(graphql)) print("REST is", round(len(rest) / len(graphql)), "times bigger")
Both answers hold what the page needs, but one is far larger. GraphQL pays for this elsewhere: caching gets harder, and any client can write an expensive query.
GraphQL returns exactly the fields you ask for. Write select(record, fields): fields are dotted paths like "name" or "avatar.url". Return a new nested dictionary holding only those fields, skipping any path that doesn't exist.
USER = {
"id": "u_1", "name": "Ana Ruiz", "email": "ana@example.com",
"avatar": {"url": "https://cdn.example/ana.png", "width": 256, "height": 256},
"plan": {"name": "team", "seats": 12},
}
def select(record, fields):
return record
print(select(USER, ["name", "avatar.url"]))
The practice API has a route that streams an embedding job as server-sent events. A real stream has more than data: lines. It has named events (event: job.progress), comments that start with a colon, and a final event whose data spans two lines, which join with a newline. Lines may end in \n or \r\n. This parser handles all of them, and the stepper after it shows the same loop on three events.
import requests def parse_events(text): events = [] for block in text.replace("\r\n", "\n").split("\n\n"): name, data = "message", [] for line in block.split("\n"): if not line or line.startswith(":"): continue field, _, value = line.partition(":") value = value.removeprefix(" ") if field == "event": name = value elif field == "data": data.append(value) if data: events.append((name, "\n".join(data))) return events r = requests.get("https://api.gradient.test/v1/events") print(r.headers["content-type"]) events = parse_events(r.text) print(len(events), "events") print([name for name, _ in events][:4]) print(events[-1])
data: first then data: second, then a blank line. How many events is that, and what is its data?One event, with the data "first\nsecond"
A blank line ends an event. Several data lines inside one event join with a newline.
from urllib.parse import urlsplit u = urlsplit("https://api.gradient.test/graphql") body = {"query": "query { campaign(id: 1) { name } }"} print(u.path, list(body))
/graphql ['query']
A GraphQL request is a POST to one path, and its body has one key, query, holding the whole question. The fields come back in the reply, not in the URL.
Write polling_vs_webhook(clients, interval_s, events_per_day): return (polls, webhooks) per day, where every client polls every interval_s seconds and webhooks equal the number of events.
def polling_vs_webhook(clients, interval_s, events_per_day): return clients, events_per_day print(polling_vs_webhook(500, 30, 2_000))
Write a sentence or two, then compare it with a good answer in the lesson.
Streams fail in ways a plain request does not, and each has a name worth knowing. A buffering proxy holds the reply until it is complete, so the user sees nothing and then everything; the cure is a Cache-Control: no-cache header, a heartbeat comment and a proxy told not to buffer. A dropped connection loses the events sent while the client was away; the event format has an id: field and a Last-Event-ID header so a client can ask to resume after the last event it saw, which the practice route supports. A client that leaves is the server's problem too: it must notice, stop the work and not bill for tokens no one will read. Streaming from the server builds that side.
Choosing is mostly a question of who talks. If one side only listens, a stream or a webhook is enough. If both sides speak at any moment, as in a shared document, a WebSocket earns its extra machinery.
Last-Event-ID
Each event may carry an id:. On reconnect the client sends the last one in Last-Event-ID, and a server that supports it resumes after that event.
A few rules cover most decisions. Pick one style for your API and use it throughout; people learn an API by guessing from the last endpoint they used. REST suits an API over your own data: nouns and verbs, easy caching and tools that understand it. JSON-RPC suits actions that are not about a noun, and it is what tool protocols use. GraphQL pays off when many different clients need different shapes, and costs you query limits and caching. For a model's reply, use server-sent events: it is one-way, it works through ordinary proxies, and a browser reads it with a few lines. Webhooks carry events between servers, and a slow poll stays as a backup for events that were lost.
In an engineer's week this shows up as a choice at design time and a bug at run time. The choice: "should the front end poll the job, or should the job stream?" The bug: a proxy that buffers the whole response, so the stream arrives in one lump, which is why servers send a heartbeat and the right headers. Goes deeper in: A chat front end in the browser reads this stream in a page, Streaming from the server writes one, and Webhooks and events verifies and retries events.
Browsers, caches and bots repeat GETs unasked
Anything may send a GET again, or send one unasked, such as a link-preview bot. A "delete" link built on GET can fire without anyone meaning it to.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Which method should never change data on the server?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write