Learn Python
Web and APIs
Call HTTP services safely and build your own API endpoints.
Call an API
python -m pip install httpximport httpx
with httpx.Client(timeout=10.0) as client:
response = client.get("https://api.mrfaws.dk/layers")
response.raise_for_status()
layers = response.json()Always set a timeout. Retry only temporary failures such as timeouts, 429 and selected 5xx responses. Use exponential backoff and a maximum attempt count. Mutations may need an idempotency key.
Build an endpoint
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {1: {"name": "Keyboard"}}
@app.get("/items/{item_id}")
def get_item(item_id: int) -> dict[str, str]:
item = items.get(item_id)
if item is None:
raise HTTPException(status_code=404, detail="Not found")
return itemBefore production, add validated schemas, authentication, persistence, logging and tests.
Exercise
Build a Map API client that lists layers and zoom limits, then caches successful responses for a short time.