APIs for AIFastAPI 0.141 · httpx2 2.13 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
19 small wins to finish your pathNext lesson

HTTP requests: method, URL, headers and body

Every API call is an HTTP request: a short, structured message saying what you want and from where. Building one in Python, without sending it, shows every part.

Example
import httpx2

request = httpx2.Request("GET", "https://api.example.com/tickets/2?upper=true")

print(request.method)
print(request.url.host)
print(request.url.path)
print(request.url.params["upper"])

The method says what kind of thing you want. GET asks for something and changes nothing. POST sends something for the server to act on. You will meet only these two for a while.

The URL says where. The host, api.example.com, is the machine. The path, /tickets/2, is the thing on it. Everything after ? is the query string, extra options written as name=value.

Headers and a body

Example
request = httpx2.Request(
    "POST",
    "https://api.example.com/v1/chat/completions",
    headers={"Authorization": "Bearer sk-local-123"},
    json={"model": "local", "messages": [{"role": "user", "content": "My parcel has not arrived"}]},
)

print(request.headers["authorization"])
print(request.headers["content-type"])
print(request.content)

Headers are labelled details about the request: who is asking, what format the body is in. Header names ignore capital letters, which is why authorization finds Authorization.

The body is the data a POST carries. Passing json= turned the dictionary into JSON text, stored it as bytes, which is what the b in front of the quote means, and added the content-type header saying it is JSON.

Nothing was sent. A request is only a description until a client sends it, which is lesson 3.

Try it yourself
  • Add &limit=5 to the first URL and print request.url.params.
  • Add a second header, "X-Request-Id": "abc", and print it back.
  • Change json= to content="hello" and print the headers. Which one disappeared?

Little by little, you're building something great.