Skip to content
Index Ai Academy
Phase 0 · Talking to APIs

How APIs work

Requests, responses, methods, status codes and headers.

About 30 minutes · Free lesson

What it covers7

First principles

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.

  1. Starting point

    Client sends GET /reports/42

  2. What changes

    Server looks for report 42

  3. Result

    A 200 response can carry the found report

Compare all three steps
  1. Starting point

    Client sends GET /reports/42

  2. What changes

    Server looks for report 42

  3. Result

    A 200 response can carry the found report

Complete and reverse the trace

Given Client sends GET /reports/42 and A 200 response can carry the found report, write down the missing step that connects them.

Compare with the worked step

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.

Check one starting point

Client sends GET /reports/42. Check that your implementation produces the result shown above.

Try it on a new case

If report 42 is missing, what status would make the situation clear?

Show worked reasoning

Return 404 for a missing resource. The client can distinguish it from a successful 200 without interpreting display text.

Run, change, and build

Check this when debugging. Thinking an API is something different from the web, rather than HTTP returning data instead of pages.

Trace the cause · Variable and output
  1. Write down the value before the line runs and predict the resulting value or printed line.
  2. Change one assigned value or input. Read the resulting value, output, or error and name the first line that explains it.
  3. Try the same reasoning on this case. If report 42 is missing, what status would make the situation clear?

Why it matters

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.

What you'll be able to do

  • Name the parts of a URL and what each one does
  • Choose the right HTTP method for reading, creating, updating and deleting
  • Read a status code and know whose problem it is
  • Turn a JSON response body into Python data
Quick check
Your code calls an API and gets back status 401. A guess: what does it most likely mean?
  1. Everything worked, and the data is in the body
  2. The page you asked for has moved to a new address
  3. The server crashed while it was handling your request
  4. The request wasn't authorized: the API key is missing or wrong
Show the answer

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.

The idea: one message out, one message back

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:

  1. a method: what you want to do (read, create, change, delete)
  2. a URL: what you want to do it to
  3. headers: extra information about the request, such as who you are and what format you're sending
  4. an optional body: data you're sending, such as a new campaign's details

Every response has three:

  1. a status code: a number saying how it went
  2. headers: information about the response
  3. a body: the data itself, often JSON
Quick check
From the lesson on JSON: a response body arrives as text, and 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. count 547
  2. 1 cmp_101
  3. 1 5470
  4. 1 547
Show the answer

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.

Anatomy of a URL

https://api.gradient.test/v1/campaigns?status=active&channel=search
PartHereWhat it does
Schemehttps://how to connect; the s means encrypted
Hostapi.gradient.testwhich server to talk to
Path/v1/campaignswhich resource on that server; v1 is the API version
Query string?status=active&channel=searchoptions 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.

Quick check
Your code must send its API key with every request. Which part of the request carries it?
  1. The status code
  2. The body
  3. A header
  4. The path
Show the answer

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.

Methods

MethodMeaningExample
GETread somethinglist campaigns
POSTcreate something, or submit data to be processedcreate a campaign; send a prompt to an LLM
PUT / PATCHreplace / partly update somethingchange a campaign's budget
DELETEremove somethingdelete 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.

Quick check
Why is it safe to repeat a GET request?
  1. Browsers cache every request, so a repeat never reaches the server
  2. It only reads, so it shouldn't change anything on the server
  3. The server ignores repeats of a request it has already seen
  4. A GET costs nothing to run, so repeats don't add any load
Show the answer

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.

Try it now

Step through two requests and their replies. Every API call is this pair of messages.

In your own words
Take https://api.gradient.test/v1/products?category=apparel apart: name each piece and what it's for.

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

In Python: reading the reply

Purpose. Send requests to the practice API and read what comes back, status first.

Status codes

The status code is the first thing to read in any response. The first digit tells you the family:

FamilyMeaningCommon codes
1xxinformational, rarely seen100 Continue
2xxsuccess200 OK, 201 Created, 204 No Content
3xxredirect: look elsewhere301 Moved Permanently, 302 Found
4xxclient error: something about your request is wrong400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
5xxserver error: the server failed500 Internal Server Error, 503 Service Unavailable

The 4xx/5xx split tells you where to look:

  • A 4xx means fix your request: a typo in the URL, a missing field, a bad API key.
  • A 5xx means the problem is on their side. Waiting and trying again may work.

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:

Quick check
What does this print?
status = 404
print(status // 100)
  1. 40
  2. 0
  3. 4
  4. 404
Show the answer

4

The first digit gives the family. 4 means the request was the problem, like asking for something that isn't there.

Quick check
You request GET https://api.gradient.test/v1/campaigns/cmp_999 and get status 404. Whose problem is it, and what should you check?
  1. Nobody's: 404 means the request worked but the result was empty
  2. Your API key's: it isn't allowed to see campaign cmp_999
  3. The server's: it's having trouble, so wait a minute and try again
  4. Yours: it points at something that doesn't exist, so check the ID or path
Show the answer

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.

Drill

Whose problem is it?

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

Headers and bodies

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

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.

Quick check
Your script gets status 503 from an API. What's the sensible next step?
  1. Give up: 503 means the API no longer exists
  2. Rewrite your request: 5xx means your request was wrong
  3. Get a new API key
  4. Wait a little and try again: 5xx means the server had a problem
Show the answer

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.

Drill

Read the error body

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

Worked example: building a request 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))
In the lesson you can change this and run it.

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.

In your own words
What does the first digit of a status code tell you?

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

In AI work: calling a model is an HTTP request

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.

Quick check
Which part of https://api.gradient.test/v1/products?category=apparel is the query string?
  1. api.gradient.test
  2. https://
  3. ?category=apparel
  4. /v1/products
Show the answer

?category=apparel

Everything after the ? is the query string: key=value options for this request.

In your own words
What are headers and the body in an HTTP request?

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 HTTP method should a request use to create a new campaign?

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

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 0 · about 32 hours of study

Tools

Python, the terminal and calling APIs 46 lessons All free
  1. Your first program FreeRun Python, print output, and read an error message without panicking.24 min
  2. Typing code exactly FreeBrackets, quotes, indentation and the look-alike characters that stop a program.26 min
  3. Variables FreeGive values names so your program can remember and reuse them.24 min
  4. Numbers and arithmetic FreeIntegers, decimals, rounding, and the math behind every metric.30 min
  5. Strings and f-strings FreeWork with text: join it, slice it, clean it, and format it.30 min
  6. Decisions with if/else FreeCompare values and choose what happens next.35 min
  7. Fractions, ratios and rates FreeShares, rates, percentage points and ratios, with Python doing the arithmetic.35 min
  8. Ranges and edges in code FreeAt least, under and between as symbols; intervals with each end in or out; bands with no gaps.32 min
  9. Lists FreeKeep many values in order, then index, slice and change them.28 min
  10. Files, folders and paths FreeWhat a file's name tells you, paths as directions through folders, and where a relative path starts.30 min
  11. Loops FreeRepeat work over every item without copy-pasting code.35 min
  12. Formulas: order, powers and rearranging FreeWork a calculation in the right order, fill in a formula, and turn it around to find what's missing.24 min
  13. Loops that add and count: sequences, sums and combinations FreeSequences that add or multiply each step, a formula for any term, and adding a sequence up.34 min
  14. Dictionaries FreeLook values up by name: the shape of almost all real-world data.40 min
  15. Functions FreePackage steps into reusable, testable pieces with inputs and outputs.35 min
  16. While loops FreeRepeat until something changes: goals reached, answers valid, tasks done.38 min
  17. Functions as values FreeStore functions, pass them in with key=, and accept any number of arguments.40 min
  18. Comprehensions FreeFilter and transform a whole collection in one readable line.38 min
  19. Errors and exceptions FreeRead tracebacks, and handle the failures you expect.38 min
  20. Finding bugs when nothing crashes FreeA method for wrong answers: expected against actual, reproduce, look inside, fix one thing.36 min
  21. Sets: unique items and fast lookups FreeDuplicates, fast membership, set operations and comparing two lists.34 min
  22. Modules and imports FreeUse Python's standard library instead of reinventing it.38 min
  23. Classes and objects FreeBundle data with the functions that work on it.38 min
  24. Inheritance and class attributes FreeBuild classes on other classes, and share values across every object.35 min
  25. Review: find the slip (Python core) FreeTen slips that run without an error, found by working a tiny input by hand, and the construct sheet for NumPy and PyTorch code.30 min
  26. JSON FreeThe text format APIs and LLMs use to exchange structured data.34 min
  27. Files and CSV data FreeRead and write files, and turn a spreadsheet export into Python data.33 min
  28. NumPy arrays FreeDo math on whole columns at once, the foundation of every ML library.30 min
  29. NumPy in practice: shapes, types and picking values FreeReshape, view and copy, where and clip, top-k, stacking and the (N, C, H, W) batch a model expects.35 min
  30. DataFrames with pandas FreeLoad a table, pick rows and columns, and summarize groups in a few lines.40 min
  31. Charts with Matplotlib FreeLine, bar, scatter, histogram and box plots, labeled and honest.42 min
  32. Project: images are arrays FreeGray, crop, brighten, watermark and palette tools built on NumPy and Pillow.45 min
  33. The terminal FreeNavigate folders and run programs by typing commands.30 min
  34. Version control with git FreeSave snapshots of your work, undo mistakes, and share code.30 min
  35. Packages and environments FreeInstall libraries with pip and keep projects isolated with venv.25 min
  36. Python on your own computer FreeInstall Python and VS Code, make a virtual environment, then run, debug and test a project.45 min
  37. How APIs work FreeRequests, responses, methods, status codes and headers.30 min
  38. Calling APIs from Python FreeSend requests, read JSON responses, and handle failures.35 min
  39. API keys and secrets FreeAuthenticate safely and keep keys out of your code.25 min
  40. Your first LLM call FreeSend messages to a model and read its reply, tokens and stop reason.30 min
  41. Capstone: ad-copy reviewer FreeCombine files, functions, JSON and an LLM call into one small tool.40 min
  42. Dates, times and time zones Freedatetime, timedelta, formats, time zones and the traps when clocks change.42 min
  43. Regular expressions FreeFind, check, extract and clean text patterns with the re module.42 min
  44. Sending email and text messages FreeEmailMessage, smtplib, mail merge and an SMS API, with secrets kept out of code.42 min
  45. Web pages: HTML and CSS FreeRead and write HTML, what forms send, CSS selectors and escaping.42 min
  46. Scraping web pages FreeBeautiful Soup, one record per item, pagination and robots.txt.45 min
Part of a free course 32 lessons

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.

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