APIs and Async · HTTP and JSON · lesson 1 of 12
Requests and responses
about 14 minutes · free · runs in your browser
Step 1 of 2
Asking a server for something
An HTTP request has a method, a URL, and optional headers and parameters. The answer has a status code, headers, and a body.
In this course you will use fake_requests, which behaves like the requests
library but answers from a scripted service instead of the network — Python compiled to
WebAssembly has no sockets. Everything you learn transfers unchanged.
import fake_requests as requests
r = requests.get("https://api.pylearn.dev/weather?city=London")
r.status_code # 200
r.ok # True for 2xx and 3xx
r.json() # {"city": "London", "temp_c": 14, ...}
r.text # the body as a string
Query parameters are better passed separately than glued onto the URL, because the library escapes them for you:
r = requests.get("https://api.pylearn.dev/weather", params={"city": "Tokyo"})
Your turn: fetch the weather for Lisbon and pull out the status code, the temperature and the condition.
You start from this, and edit it in the browser:
import fake_requests as requests
# Fetch https://api.pylearn.dev/weather for Lisbon.
# Set status, temp and condition.
Step 2 of 2
Turning a response into your own shape
An API gives you its structure; your program usually wants a different one. Doing that conversion at the boundary — rather than passing raw response dictionaries through your whole codebase — is what keeps a change at the API from rippling everywhere.
Your turn: write get_summary(city) returning
{"city": ..., "temp_c": ..., "summary": "London: 14C, cloudy"} for a city that
exists.
You start from this, and edit it in the browser:
import fake_requests as requests
BASE = "https://api.pylearn.dev"
def get_summary(city):
# Fetch the weather and return your own shape.
pass