[concept]Web & APIs
Requests Basics
# theory
fetching: requests vs pyfetch
In a regular Python script you use the requests library:
import requests
response = requests.get("https://api.example.com/data")
print(response.status_code)
print(response.json())
This site runs Python in a browser Web Worker via Pyodide, so the network goes through the browser's fetch instead. The Pyodide-native wrapper is pyodide.http.pyfetch:
from pyodide.http import pyfetch
response = await pyfetch("https://jsonplaceholder.typicode.com/users/1")
print(response.status)
data = await response.json()
print(data)
Same shape, two differences worth knowing:
- It's async. You must
awaitboth the fetch and.json(). - It runs from the browser, so the target API has to send CORS headers. Sites that don't, you can't reach directly.
When you ship a real script you'll write requests.get. The patterns translate.
status, json, errors
response = await pyfetch(url)
response.status # 200, 404, 500 ...
response.ok # True if status < 400
await response.string() # raw text
await response.json() # parsed JSON
Handle failures explicitly. Network errors raise; bad status codes don't:
try:
response = await pyfetch(url)
if response.status >= 400:
print(f"HTTP {response.status}")
else:
data = await response.json()
except Exception as e:
print(f"request failed: {e}")
query params
pyfetch doesn't have a params= keyword like requests does. Build the query string yourself:
from urllib.parse import urlencode
params = {"userId": 1}
url = f"https://jsonplaceholder.typicode.com/posts?{urlencode(params)}"
response = await pyfetch(url)
posts = await response.json()
print(f"{len(posts)} posts for user 1")
public test API
Examples below hit jsonplaceholder.typicode.com. It's a free, CORS-friendly fake API with users, posts, comments, todos. Real HTTP, real JSON, no auth required. Good for practice without spinning up your own backend.
# examples [3]
Hit a public CORS-friendly API and read the response. Real HTTP, real status code, real JSON.
GET a collection, parse it, do real work on it. Same pattern you'd use with a paginated production API.
Hit a URL that returns 404. response.ok is False; nothing raises. You check.
# challenges [2]
# project
# project-challenge
thread: Sales Performance Dashboard · reward: 50 xp
# brief
The inventory system returns sales data via an API. Process the simulated API response to extract sales records and calculate summary statistics.
# task