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.
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
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.
- Add
&limit=5to the first URL and printrequest.url.params. - Add a second header,
"X-Request-Id": "abc", and print it back. - Change
json=tocontent="hello"and print the headers. Which one disappeared?
Little by little, you're building something great.