Free Python for AI course
Learn Python from your first line of code to your first call to a language model, with nothing to install.
Requests, responses, methods, status codes and headers.
What does the client put on the wire when it asks for one report?
An HTTP request identifies an action and target and can carry headers or a body. The response carries a status with its own headers and optional body.
Client sends GET /reports/42
Server looks for report 42
A 200 response can carry the found report
Client sends GET /reports/42
Server looks for report 42
A 200 response can carry the found report
Given Client sends GET /reports/42 and A 200 response can carry the found report, write down the missing step that connects them.
Server looks for report 42
Now take Server looks for report 42 and the result above. Write an input and an implementation that could produce this trace.
Client sends GET /reports/42. Check that your implementation produces the result shown above.
If report 42 is missing, what status would make the situation clear?
Return 404 for a missing resource. The client can distinguish it from a successful 200 without interpreting display text.
Check this when debugging. Thinking an API is something different from the web, rather than HTTP returning data instead of pages.
Every call to an LLM is an HTTP request. So is every integration you've used in marketing: pulling numbers from an ad platform, adding a contact to a CRM, sending an email through a delivery service. When an AI agent "uses a tool", it's usually making one of these requests. Learn to read requests and responses, and most API errors explain themselves.
The request wasn't authorized: the API key is missing or wrong
Status codes in the 400s mean the request had a problem; 401 means the server doesn't know who you are, usually because of a missing or wrong key. You'll learn to read a response's status first, every time.
This lesson rests on JSON: the data in most requests and replies is JSON text.
HTTP is the set of rules browsers and servers use to talk. It works like ordering at a counter. You (the client) place an order (the request), and the kitchen (the server) hands something back (the response). When you open a web page, your browser is the client, and the response is the page for it to draw.
An API (application programming interface) uses exactly the same rules. But it's built for programs rather than people. Instead of a web page, it replies with data, almost always as JSON. Your code is the client.
Every request has four parts:
Every response has three:
json.loads turns it into Python data. What does this print?import json body = '{"data": [{"id": "cmp_101", "clicks": 5470}], "count": 1}' result = json.loads(body) print(result["count"], result["data"][0]["clicks"] // 10)
1 547
After json.loads, result is a dictionary. Its count is 1, and its data is a list whose first item is a dictionary with 5,470 clicks, a real number that can be divided. Every API in this lesson answers with a body like this one.
https://api.gradient.test/v1/campaigns?status=active&channel=search
| Part | Here | What it does |
|---|---|---|
| Scheme | https:// | how to connect; the s means encrypted |
| Host | api.gradient.test | which server to talk to |
| Path | /v1/campaigns | which resource on that server; v1 is the API version |
| Query string | ?status=active&channel=search | options for this request, as key=value pairs joined by & |
You know query strings already: UTM tags are exactly this. In ?utm_source=newsletter&utm_campaign=spring, the analytics tool reads the key-value pairs after the ?. An API reads them the same way. Here they filter which campaigns to return.
A header
Headers carry information about the request itself, such as who you are. The key goes there, not in the URL or the data.
api.gradient.test is the academy's practice API. It pretends to be an ad platform with six campaigns and a small product catalog. You can experiment without breaking anything.
| Method | Meaning | Example |
|---|---|---|
GET | read something | list campaigns |
POST | create something, or submit data to be processed | create a campaign; send a prompt to an LLM |
PUT / PATCH | replace / partly update something | change a campaign's budget |
DELETE | remove something | delete a draft |
A GET should never change anything on the server. That's why it's safe to repeat. Calls to an LLM are POST requests, because you send a body containing your messages.
It only reads, so it shouldn't change anything on the server
Reading twice gives you the same data and leaves the server as it was. Repeating a POST might create something twice.
Step through two requests and their replies. Every API call is this pair of messages.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. Send requests to the practice API and read what comes back, status first.
The status code is the first thing to read in any response. The first digit tells you the family:
| Family | Meaning | Common codes |
|---|---|---|
| 1xx | informational, rarely seen | 100 Continue |
| 2xx | success | 200 OK, 201 Created, 204 No Content |
| 3xx | redirect: look elsewhere | 301 Moved Permanently, 302 Found |
| 4xx | client error: something about your request is wrong | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
| 5xx | server error: the server failed | 500 Internal Server Error, 503 Service Unavailable |
The 4xx/5xx split tells you where to look:
Two codes you'll see a lot with LLM APIs: 401, meaning your API key is missing or wrong, and 429, meaning you're sending requests faster than you're allowed to.
401 and 403 sound alike. 401 means "I can't tell who you are": no key, or a key the API doesn't recognize. 403 means "I know who you are, and you're not allowed to do this": a valid key without permission. A model API answers a wrong key with 401.
Send some requests and watch the codes:
status = 404 print(status // 100)
4
The first digit gives the family. 4 means the request was the problem, like asking for something that isn't there.
GET https://api.gradient.test/v1/campaigns/cmp_999 and get status 404. Whose problem is it, and what should you check?Yours: it points at something that doesn't exist, so check the ID or path
404 is a client error: no resource at that path. Retrying won't help; fixing the ID will. A bad key would be 401 or 403.
Write whose_problem(status) that returns "ok" for a 2xx status, "redirect" for 3xx, "yours" for 4xx and "theirs" for 5xx.
def whose_problem(status): ...
Headers are Name: value lines that travel with a request or response. A few you'll see constantly:
Content-Type: application/json says the body is JSON.X-Api-Key: ... or Authorization: Bearer ... carries your credentials (covered in the API keys lesson).Accept: application/json asks for JSON back.The body of a request or response is just text. When it's JSON, you read it with json.loads and write it with json.dumps, as in JSON.
Here is a response body from the practice API, as one string:
import json body = """{"data": [{"id": "cmp_101", "name": "Spring Sale - Search", "clicks": 5470}, {"id": "cmp_104", "name": "Newsletter Promo - Email", "clicks": 1920}], "count": 2}""" result = json.loads(body) print(type(result)) print(result["count"]) for campaign in result["data"]: print(campaign["name"], campaign["clicks"])
Error responses are JSON too, and a well-designed API puts a readable message inside:
import json status = 404 body = '{"error": {"type": "not_found", "message": "No campaign with id cmp_999."}}' if status >= 400: details = json.loads(body) print("Request failed with", status) print(details["error"]["message"])
When a request fails, print the status code and the body. The answer to "why didn't this work?" is usually sitting in that message.
Wait a little and try again: 5xx means the server had a problem
5xx errors are on the server's side, and they're often short-lived. A 4xx is the one that means fix your request.
An API that refuses a request sends the reason in the JSON body, under error and then message. Write error_message(status, body) that returns None when the status is below 400, and otherwise the message text from the body.
import json def error_message(status, body): ...
You want to create a campaign. The API expects a JSON body with name and budget. Build the data as a Python dictionary, then turn it into the text that would be sent.
import json new_campaign = { "name": "Summer Launch - Social", "budget": 1500, "channel": "social", } body = json.dumps(new_campaign) print(body) print(type(body))
It prints {"name": "Summer Launch - Social", "budget": 1500, "channel": "social"}, then <class 'str'>: the body is now text, ready to send.
You always build request data as normal Python, a dictionary here. Turn it into JSON text only at the moment of sending. Notice the output uses double quotes. That's JSON's rule, and json.dumps handles it for you. In Calling APIs from Python, the requests library does this step for you when you pass json=new_campaign.
Write a sentence or two, then compare it with a good answer in the lesson.
Purpose. A model call is the same message pair you've been reading, so the same habits work: read the status first, then the body.
The Messages API takes a POST with the key in a header and your messages in the body. It answers 200 with the reply and token counts, 401 for a bad key, and 429 when you send too fast. A 429 carries a Retry-After header: how long to wait. Real services limit your speed, so you'll meet that reply the first time you send a hundred requests in a loop.
https://api.gradient.test/v1/products?category=apparel is the query string??category=apparel
Everything after the ? is the query string: key=value options for this request.
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 HTTP method should a request use to create a new campaign?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Learn Python from your first line of code to your first call to a language model, with nothing to install.
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