typestar

Request bodies in Python

A pydantic model as a parameter means the body is validated for you.

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field


class RunIn(BaseModel):
    lang: str
    tpm: float = Field(gt=0)


class RunOut(BaseModel):
    lang: str
    stars: int


app = FastAPI()


@app.post("/results", response_model=RunOut, status_code=201)
def save(run: RunIn):
    return {"lang": run.lang, "stars": 3 if run.tpm >= 100 else 1,
            "secret": "filtered out"}


client = TestClient(app)
posted = client.post("/results", json={"lang": "python", "tpm": 104})
print(posted.status_code, posted.json())
print(client.post("/results", json={"lang": "x", "tpm": -1}).status_code)

How it works

  1. The model becomes the request schema.
  2. response_model filters and documents what goes back.
  3. A validation failure is a 422 with the field path.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
621
Tokens
187
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 102 seconds.

Type this snippet

Step 3 of 4 in FastAPI routes, step 8 of 19 in Web services & data access.

← Previous Next →