Codzy

Web: a mini JSON API

A web API is a program that answers requests with data, almost always as JSON. It's organised in routes: a method + a path (e.g. GET /tasks/2) trigger a function, which returns a status code and a body.

That's exactly what FastAPI or Flask do, plus the networking. Good habits: 200 when all is well, 404 if the resource doesn't exist, 405 if the method isn't allowed, and always a readable JSON response, even for an error. json.dumps turns a Python object into JSON text.

import json

users = {1: {"name": "Lina"}, 2: {"name": "Omar"}}

def get_user(user_id):
    if user_id in users:
        return 200, users[user_id]
    return 404, {"error": "user not found"}

for uid in (1, 3):
    status, body = get_user(uid)
    print(status, json.dumps(body))

Start the lesson