{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"anatomy-of-a-request","title":"What a request is made of, and how to see the one you actually sent","url":"https://addaly.com/learn/python-for-ai/anatomy-of-a-request","position":50,"of":89,"minutes":8,"answer":"A request is a method, a URL with a query string, headers and an optional body; when a call fails, print the request Python built rather than the one you think you wrote.","keyIdea":"A request is a method, a URL with a query string, headers and an optional body; when a call fails, print the request Python built rather than the one you think you wrote."},"body":{"format":"markdown","text":"## Four parts, every time\n\nEvery HTTP request your program sends has the same four parts, and `requests` builds all of them from the arguments you pass. When a call misbehaves, the fault is in one of these four, and knowing which one is most of the diagnosis.\n\n1. **The method.** `GET` asks for something; `POST` sends something; `PUT`, `PATCH` and `DELETE` change or remove. Model APIs are almost entirely `POST`, because the prompt travels in the body.\n2. **The URL, including the query string.** Everything after `?` is a set of `key=value` pairs separated by `&`.\n3. **The headers.** Key-value metadata: who you are, what format you are sending, what format you will accept.\n4. **The body.** Optional. Bytes, usually JSON text, sent with `POST`.\n\n## The query string, and why `params=` exists\n\nYou can build a URL by hand:\n\n```python\nurl = f\"https://example.com/search?q={query}&page=2\"\n```\n\nThis breaks the first time `query` contains a space, an ampersand, a plus sign or a letter outside ASCII. A space must become `%20`, `&` must become `%26`, and `é` must become `%C3%A9`. Forget any of these and the server reads a different query from the one you meant. It will not tell you; it will answer the question it received.\n\n`requests` does the encoding when you hand it a dict:\n\n```python\nr = requests.get(\n    \"https://example.com/search\",\n    params={\"q\": \"café au lait\", \"page\": 2},\n    timeout=10,\n)\nprint(r.request.url)\n# https://example.com/search?q=caf%C3%A9+au+lait&page=2\n```\n\nNote the `+` for a space. Both `+` and `%20` are valid in a query string, and servers accept either. A value of `None` in the dict is dropped rather than sent as the string `None`, and a list value is repeated: `{\"tag\": [\"a\", \"b\"]}` becomes `tag=a&tag=b`.\n\n## Headers: the ones you must send\n\nTwo headers matter for nearly every API call.\n\n**Authentication.** Most providers use one of two shapes:\n\n```python\nheaders = {\"Authorization\": f\"Bearer {key}\"}     # OpenAI, most others\nheaders = {\"x-api-key\": key}                      # Anthropic\n```\n\nGet the header name wrong and you receive a 401 that looks exactly like a bad key. When a 401 arrives and you are sure of the key, check the header name before anything else.\n\n**Content type.** When you send a body, the server needs to know how to read it. Pass `json=` and `requests` sets `Content-Type: application/json` and serialises the dict for you. Pass `data=` with a dict and it sends form-encoded pairs instead, with a different content type, and an API expecting JSON will reject it or, worse, read an empty body. This is the single most common cause of a 400 with a message like \"missing field: model\" when the field is plainly there.\n\n```python\nr = requests.post(url, json={\"model\": m, \"messages\": msgs})   # JSON body\nr = requests.post(url, data={\"model\": m})                     # form body — wrong for a model API\n```\n\n`requests` also sends a `User-Agent` of `python-requests/2.x` by default. Some services block it. Setting your own, naming your project, is polite and occasionally necessary.\n\n## Seeing what you sent\n\nThe request you wrote and the request that left your machine are different objects. The second is available after the call:\n\n```python\nr = requests.post(url, headers=headers, json=payload, timeout=30)\n\nprint(r.request.method)\nprint(r.request.url)\nprint(r.request.headers)\nprint(r.request.body[:200])\n```\n\nPrint these before reading the response when something is wrong. Nine times out of ten the bug is visible here: a header name with a typo, a body that is form-encoded, a URL with a doubled slash, a key that is the string `None` because the environment variable was never set.\n\nNever print the full `Authorization` header into a log that anyone else can see. Print `r.request.headers[\"Authorization\"][:12]` and check that it starts with `Bearer sk-`.\n\n## An echo server for experiments\n\nThe free service at `httpbin.org` returns whatever you sent it, as JSON, so you can see a request from the server's side:\n\n```python\nr = requests.post(\n    \"https://httpbin.org/post\",\n    params={\"q\": \"café\"},\n    headers={\"X-Demo\": \"yes\"},\n    json={\"a\": 1},\n    timeout=10,\n)\nprint(r.json()[\"args\"])     # {'q': 'café'}\nprint(r.json()[\"json\"])     # {'a': 1}\nprint(r.json()[\"headers\"][\"X-Demo\"])\n```\n\nTry `data=` instead of `json=` and watch `json` become `None` and `form` fill in. That one experiment is worth a chapter.\n\nIf you would rather not send anything off your machine, `python -m http.server 8000` serves the current folder and prints every request line it receives.\n\n## The response has the same anatomy\n\nA response is a status code, headers and a body. Two response headers earn their keep:\n\n- `Content-Type` tells you whether `r.json()` will work. An error page arrives as `text/html`, and calling `.json()` on it raises rather than returning your data.\n- `Retry-After` on a 429 or 503 tells you how many seconds to wait. A later lesson uses it.\n\n`r.headers` is a case-insensitive dict, so `r.headers[\"content-type\"]` and `r.headers[\"Content-Type\"]` both work.\n\n## Where this is heading\n\nYou have now seen a request as the server sees it. The rest of the module builds outward: reusing the connection, timing out and retrying without paying twice, and walking a result that arrives in pages."},"check":{"question":"A developer calls `requests.get(url, params={\"q\": \"café au lait\", \"page\": 2})` and the server returns results for the wrong search. Which check would settle whether the problem is on their side?","options":[{"text":"Print `r.request.url` and compare the encoded query string with what the API documentation expects.","correct":true},{"text":"Switch to `requests.post` with the same dict as `json=`, because query strings cannot carry non-ASCII characters.","correct":false,"tempting":"Query strings can carry any character once percent-encoded, which `params=` does automatically; changing the method changes the request the server receives entirely."},{"text":"Add `headers={\"Content-Type\": \"application/json\"}` so the server parses the parameters correctly.","correct":false,"tempting":"A GET with `params=` has no body, so a body content type describes nothing and the server will ignore or reject it."},{"text":"Call `r.json()` and inspect the `error` key, which every API populates when a parameter is wrong.","correct":false,"tempting":"There is no such convention; a server that misread the query returns a successful-looking 200 with the wrong data, and the response cannot show what was sent."}]},"prev":{"slug":"first-api-call","title":"Calling an API for the first time","url":"https://addaly.com/learn/python-for-ai/first-api-call"},"next":{"slug":"sessions-and-connection-reuse","title":"Sessions: paying for the handshake once instead of every call","url":"https://addaly.com/learn/python-for-ai/sessions-and-connection-reuse"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'What a request is made of, and how to see the one you actually sent', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/anatomy-of-a-request (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"What a request is made of, and how to see the one you actually sent","courseTitle":"Python, from Zero, for AI","module":{"index":6,"slug":"talking-to-a-service","title":"Talking to a service: HTTP from Python, done properly"},"answer":null,"keyIdea":"A request is a method, a URL with a query string, headers and an optional body; when a call fails, print the request Python built rather than the one you think you wrote.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"four-parts-every-time","runs":[{"text":"Four parts, every time"}]},{"t":"p","runs":[{"text":"Every HTTP request your program sends has the same four parts, and "},{"text":"requests","code":true},{"text":" builds all of them from the arguments you pass. When a call misbehaves, the fault is in one of these four, and knowing which one is most of the diagnosis."}]},{"t":"ol","start":1,"items":[[{"text":"The method.","b":true},{"text":" "},{"text":"GET","code":true},{"text":" asks for something; "},{"text":"POST","code":true},{"text":" sends something; "},{"text":"PUT","code":true},{"text":", "},{"text":"PATCH","code":true},{"text":" and "},{"text":"DELETE","code":true},{"text":" change or remove. Model APIs are almost entirely "},{"text":"POST","code":true},{"text":", because the prompt travels in the body."}],[{"text":"The URL, including the query string.","b":true},{"text":" Everything after "},{"text":"?","code":true},{"text":" is a set of "},{"text":"key=value","code":true},{"text":" pairs separated by "},{"text":"&","code":true},{"text":"."}],[{"text":"The headers.","b":true},{"text":" Key-value metadata: who you are, what format you are sending, what format you will accept."}],[{"text":"The body.","b":true},{"text":" Optional. Bytes, usually JSON text, sent with "},{"text":"POST","code":true},{"text":"."}]]},{"t":"h2","id":"the-query-string-and-why-params-exists","runs":[{"text":"The query string, and why "},{"text":"params=","code":true},{"text":" exists"}]},{"t":"p","runs":[{"text":"You can build a URL by hand:"}]},{"t":"code","lang":"python","label":"Python","text":"url = f\"https://example.com/search?q={query}&page=2\""},{"t":"p","runs":[{"text":"This breaks the first time "},{"text":"query","code":true},{"text":" contains a space, an ampersand, a plus sign or a letter outside ASCII. A space must become "},{"text":"%20","code":true},{"text":", "},{"text":"&","code":true},{"text":" must become "},{"text":"%26","code":true},{"text":", and "},{"text":"é","code":true},{"text":" must become "},{"text":"%C3%A9","code":true},{"text":". Forget any of these and the server reads a different query from the one you meant. It will not tell you; it will answer the question it received."}]},{"t":"p","runs":[{"text":"requests","code":true},{"text":" does the encoding when you hand it a dict:"}]},{"t":"code","lang":"python","label":"Python","text":"r = requests.get(\n    \"https://example.com/search\",\n    params={\"q\": \"café au lait\", \"page\": 2},\n    timeout=10,\n)\nprint(r.request.url)\n# https://example.com/search?q=caf%C3%A9+au+lait&page=2"},{"t":"p","runs":[{"text":"Note the "},{"text":"+","code":true},{"text":" for a space. Both "},{"text":"+","code":true},{"text":" and "},{"text":"%20","code":true},{"text":" are valid in a query string, and servers accept either. A value of "},{"text":"None","code":true},{"text":" in the dict is dropped rather than sent as the string "},{"text":"None","code":true},{"text":", and a list value is repeated: "},{"text":"{\"tag\": [\"a\", \"b\"]}","code":true},{"text":" becomes "},{"text":"tag=a&tag=b","code":true},{"text":"."}]},{"t":"h2","id":"headers-the-ones-you-must-send","runs":[{"text":"Headers: the ones you must send"}]},{"t":"p","runs":[{"text":"Two headers matter for nearly every API call."}]},{"t":"p","runs":[{"text":"Authentication.","b":true},{"text":" Most providers use one of two shapes:"}]},{"t":"code","lang":"python","label":"Python","text":"headers = {\"Authorization\": f\"Bearer {key}\"}     # OpenAI, most others\nheaders = {\"x-api-key\": key}                      # Anthropic"},{"t":"p","runs":[{"text":"Get the header name wrong and you receive a 401 that looks exactly like a bad key. When a 401 arrives and you are sure of the key, check the header name before anything else."}]},{"t":"p","runs":[{"text":"Content type.","b":true},{"text":" When you send a body, the server needs to know how to read it. Pass "},{"text":"json=","code":true},{"text":" and "},{"text":"requests","code":true},{"text":" sets "},{"text":"Content-Type: application/json","code":true},{"text":" and serialises the dict for you. Pass "},{"text":"data=","code":true},{"text":" with a dict and it sends form-encoded pairs instead, with a different content type, and an API expecting JSON will reject it or, worse, read an empty body. This is the single most common cause of a 400 with a message like “missing field: model” when the field is plainly there."}]},{"t":"code","lang":"python","label":"Python","text":"r = requests.post(url, json={\"model\": m, \"messages\": msgs})   # JSON body\nr = requests.post(url, data={\"model\": m})                     # form body — wrong for a model API"},{"t":"p","runs":[{"text":"requests","code":true},{"text":" also sends a "},{"text":"User-Agent","code":true},{"text":" of "},{"text":"python-requests/2.x","code":true},{"text":" by default. Some services block it. Setting your own, naming your project, is polite and occasionally necessary."}]},{"t":"h2","id":"seeing-what-you-sent","runs":[{"text":"Seeing what you sent"}]},{"t":"p","runs":[{"text":"The request you wrote and the request that left your machine are different objects. The second is available after the call:"}]},{"t":"code","lang":"python","label":"Python","text":"r = requests.post(url, headers=headers, json=payload, timeout=30)\n\nprint(r.request.method)\nprint(r.request.url)\nprint(r.request.headers)\nprint(r.request.body[:200])"},{"t":"p","runs":[{"text":"Print these before reading the response when something is wrong. Nine times out of ten the bug is visible here: a header name with a typo, a body that is form-encoded, a URL with a doubled slash, a key that is the string "},{"text":"None","code":true},{"text":" because the environment variable was never set."}]},{"t":"p","runs":[{"text":"Never print the full "},{"text":"Authorization","code":true},{"text":" header into a log that anyone else can see. Print "},{"text":"r.request.headers[\"Authorization\"][:12]","code":true},{"text":" and check that it starts with "},{"text":"Bearer sk-","code":true},{"text":"."}]},{"t":"h2","id":"an-echo-server-for-experiments","runs":[{"text":"An echo server for experiments"}]},{"t":"p","runs":[{"text":"The free service at "},{"text":"httpbin.org","code":true},{"text":" returns whatever you sent it, as JSON, so you can see a request from the server’s side:"}]},{"t":"code","lang":"python","label":"Python","text":"r = requests.post(\n    \"https://httpbin.org/post\",\n    params={\"q\": \"café\"},\n    headers={\"X-Demo\": \"yes\"},\n    json={\"a\": 1},\n    timeout=10,\n)\nprint(r.json()[\"args\"])     # {'q': 'café'}\nprint(r.json()[\"json\"])     # {'a': 1}\nprint(r.json()[\"headers\"][\"X-Demo\"])"},{"t":"p","runs":[{"text":"Try "},{"text":"data=","code":true},{"text":" instead of "},{"text":"json=","code":true},{"text":" and watch "},{"text":"json","code":true},{"text":" become "},{"text":"None","code":true},{"text":" and "},{"text":"form","code":true},{"text":" fill in. That one experiment is worth a chapter."}]},{"t":"p","runs":[{"text":"If you would rather not send anything off your machine, "},{"text":"python -m http.server 8000","code":true},{"text":" serves the current folder and prints every request line it receives."}]},{"t":"h2","id":"the-response-has-the-same-anatomy","runs":[{"text":"The response has the same anatomy"}]},{"t":"p","runs":[{"text":"A response is a status code, headers and a body. Two response headers earn their keep:"}]},{"t":"ul","items":[[{"text":"Content-Type","code":true},{"text":" tells you whether "},{"text":"r.json()","code":true},{"text":" will work. An error page arrives as "},{"text":"text/html","code":true},{"text":", and calling "},{"text":".json()","code":true},{"text":" on it raises rather than returning your data."}],[{"text":"Retry-After","code":true},{"text":" on a 429 or 503 tells you how many seconds to wait. A later lesson uses it."}]]},{"t":"p","runs":[{"text":"r.headers","code":true},{"text":" is a case-insensitive dict, so "},{"text":"r.headers[\"content-type\"]","code":true},{"text":" and "},{"text":"r.headers[\"Content-Type\"]","code":true},{"text":" both work."}]},{"t":"h2","id":"where-this-is-heading","runs":[{"text":"Where this is heading"}]},{"t":"p","runs":[{"text":"You have now seen a request as the server sees it. The rest of the module builds outward: reusing the connection, timing out and retrying without paying twice, and walking a result that arrives in pages."}]}],"check":{"question":[{"text":"A developer calls "},{"text":"requests.get(url, params={\"q\": \"café au lait\", \"page\": 2})","code":true},{"text":" and the server returns results for the wrong search. Which check would settle whether the problem is on their side?"}],"options":[{"text":[{"text":"Print "},{"text":"r.request.url","code":true},{"text":" and compare the encoded query string with what the API documentation expects."}],"correct":true,"tempting":null},{"text":[{"text":"Switch to "},{"text":"requests.post","code":true},{"text":" with the same dict as "},{"text":"json=","code":true},{"text":", because query strings cannot carry non-ASCII characters."}],"correct":false,"tempting":[{"text":"Query strings can carry any character once percent-encoded, which "},{"text":"params=","code":true},{"text":" does automatically; changing the method changes the request the server receives entirely."}]},{"text":[{"text":"Add "},{"text":"headers={\"Content-Type\": \"application/json\"}","code":true},{"text":" so the server parses the parameters correctly."}],"correct":false,"tempting":[{"text":"A GET with "},{"text":"params=","code":true},{"text":" has no body, so a body content type describes nothing and the server will ignore or reject it."}]},{"text":[{"text":"Call "},{"text":"r.json()","code":true},{"text":" and inspect the "},{"text":"error","code":true},{"text":" key, which every API populates when a parameter is wrong."}],"correct":false,"tempting":[{"text":"There is no such convention; a server that misread the query returns a successful-looking 200 with the wrong data, and the response cannot show what was sent."}]}],"order":[3,2,1,0],"why":null},"prev":{"slug":"first-api-call","title":"Calling an API for the first time","minutes":9},"next":{"slug":"sessions-and-connection-reuse","title":"Sessions: paying for the handshake once instead of every call","minutes":7}}}