Skip to content
Index Ai Academy
Phase 8 · HTTP from the wire up

API styles

REST, RPC, GraphQL, gRPC and streaming: what each is for.

About 35 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

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.

  1. Starting point

    A client needs the current job snapshot

  2. What changes

    Request the job resource by its ID

  3. Result

    The response carries the current representation

Compare all three steps
  1. Starting point

    A client needs the current job snapshot

  2. What changes

    Request the job resource by its ID

  3. Result

    The response carries the current representation

Complete and reverse the trace

Given A client needs the current job snapshot and The response carries the current representation, write down the missing step that connects them.

Compare with the worked step

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.

Check one starting point

A client needs the current job snapshot. Check that your implementation produces the result shown above.

Try it on a new case

A client needs to see each model token as it arrives. What kind of exchange fits?

Show worked reasoning

Use a streaming response. The client can act on partial output before the server completes the generation.

Run, change, and build

Check this when debugging. Calling any JSON-over-HTTP API REST, even one URL that takes an action name.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. A client needs to see each model token as it arrives. What kind of exchange fits?

Why it matters

"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.

What you'll be able to do

  • Write the same request as REST, JSON-RPC and GraphQL, and say what each puts where
  • Explain what GraphQL solves and what it moves onto the server
  • Choose between polling, webhooks, server-sent events and WebSockets for live updates
  • Parse an event stream with named events, comments and multi-line data
Quick check
In a REST API, which request fetches order 88?
  1. DELETE /orders/88
  2. GET /orders/88
  3. POST /getOrder?id=88
  4. GET /fetchOrderNumber88
Show the answer

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.

The idea: one question, three envelopes

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:

actionmethod and pathsuccess status
list campaignsGET /campaigns200
read oneGET /campaigns/cmp_103200
create onePOST /campaigns201
replace onePUT /campaigns/cmp_103200
change some fieldsPATCH /campaigns/cmp_103200
delete oneDELETE /campaigns/cmp_103204 (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.

Quick check
A teammate's endpoint is POST /api with the body {"action": "delete_user", "id": 7}. Which style is it?
  1. RPC: the action's name is in the body
  2. GraphQL, because it has one URL
  3. REST, because it returns JSON
  4. None of them: it is not an API
Show the answer

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.

Quick check
Recall: a request is a request line, headers, a blank line and a body. What does this print?
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)
  1. POST 2 application/json
  2. /v1/campaigns 2 {"name": "Spring"}
  3. POST 3 {"name": "Spring"}
  4. POST 2 {"name": "Spring"}
Show the answer

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.

Try it now

Polling asked twice for nothing. The webhook arrived once, with the news.

In your own words
What does REST put in the URL, what does JSON-RPC put in the body, and what does GraphQL let the client choose?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: the same question three ways, and a stream

The three requests for one campaign, as data. All three travel over the same HTTP.

Worked example

The same request in three styles

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 ''}")
It runs right here in your browser, with nothing to install.

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.

Worked example

Over-fetching, measured

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")
In the lesson you can change this and run it.

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.

Drill

Ask for just the fields you need

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"]))
In the lesson, your code is checked as you write it.

Read a real event stream

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])
Quick check
A stream block reads data: first then data: second, then a blank line. How many events is that, and what is its data?
  1. No event, since it has no event: line
  2. Two events, "first" and "second"
  3. One event, with the data "first\nsecond"
  4. One event, with only "second"
Show the answer

One event, with the data "first\nsecond"

A blank line ends an event. Several data lines inside one event join with a newline.

Quick check
What does this print?
from urllib.parse import urlsplit
u = urlsplit("https://api.gradient.test/graphql")
body = {"query": "query { campaign(id: 1) { name } }"}
print(u.path, list(body))
  1. /graphql ['campaign']
  2. /campaigns/1 ['name']
  3. /graphql ['query']
  4. /graphql ['name']
Show the answer

/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.

Drill

What polling costs

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))
In the lesson, your code is checked as you write it.
In your own words
When does each of polling, webhooks, server-sent events and WebSockets fit?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: a model's reply is a stream

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.

Quick check
A stream cuts out after event 7 and the client reconnects. Which header lets it ask the server to continue after the last event it received?
  1. Retry-After
  2. Content-Length
  3. Last-Event-ID
  4. If-None-Match
Show the answer

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.

What to choose, and what it costs

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.

Quick check
Why must a GET never change anything?
  1. Browsers, caches and bots repeat GETs unasked
  2. A GET request can't carry any data
  3. A GET is slower than a POST
  4. GET requests are never encrypted
Show the answer

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.

In your own words
Why does an AI product stream a model's reply with server-sent events?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

Which method should never change data on the server?

  1. GET
  2. POST
  3. PATCH
  4. DELETE

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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