← Back to FastAPI, page 4

fastapi-0064 · Easy fresher

How does FastAPI convert path, query and body values to Python types such as int, bool, UUID, date and datetime?

FastAPI reads the type hints on your function and Pydantic parses the raw strings or JSON values into those types: int and float from numeric strings, bool from true, 1, yes, on (and their opposites), UUID from canonical strings, date and datetime from ISO 8601, Decimal from numbers or strings, Enum from values, and lists or sets from repeated keys or arrays. Invalid values return 422, so your function only sees valid typed data.

Full answer

Because the signature says what the data should be, FastAPI does parsing, validation and documentation in one step:

python
class Price(BaseModel):
    amount: Decimal


@app.get("/price", response_model=Price)
def price_with_model():
    return {"amount": Decimal("199.90")}


@app.get("/events/{event_id}")
def event(event_id: UUID, day: date, at: datetime | None = None, urgent: bool = False, price: Decimal = Decimal("0")):
  • UUID: accepts 36-character hyphenated strings (and a few other UUID forms); invalid text gives 422.
  • date and datetime: ISO 8601 (2026-12-04, 2026-12-04T10:30:00+05:30). A Z or offset yields an aware datetime; no offset yields a naive one. Store and compare UTC in your system, convert at the edges.
  • bool in query strings: true, false, 1, 0, yes, no, on, off (case-insensitive).
  • int and float: numeric strings are accepted in lax mode; "1.5" for an int is rejected, while 1.0 as a JSON number is accepted for int.
  • Decimal: use for money. When the value passes through a response model, Pydantic v2 serialises it as a JSON string ("199.90"), which keeps it exact. A bare Decimal inside a returned dict with no response model goes through jsonable_encoder and becomes a float (199.9), so declare a response model for money fields.
  • time, timedelta (ISO 8601 durations such as PT1H), bytes, Path, Enum, Literal, HttpUrl, EmailStr (needs email-validator).
  • Union types try members in "smart" order; avoid unions of overlapping scalars (int | str), which can surprise.

Return values are converted back to JSON: dates to ISO strings, UUID to string, Enum to its value. The function receives real Python objects, so you can compare dates, do arithmetic with Decimal and use uuid.version.

Gotchas: float binary rounding for money, naive vs aware datetimes in comparisons (TypeError), and time zones: ISO strings without offsets are ambiguous.

python
from datetime import date, datetime, timedelta
from decimal import Decimal
from enum import Enum
from uuid import UUID

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

app = FastAPI()


class Mode(str, Enum):
    online = "online"
    campus = "campus"


class Price(BaseModel):
    amount: Decimal


@app.get("/price", response_model=Price)
def price_with_model():
    return {"amount": Decimal("199.90")}


@app.get("/events/{event_id}")
def event(event_id: UUID, day: date, at: datetime | None = None, urgent: bool = False,
          price: Decimal = Decimal("0"), length: timedelta = timedelta(hours=1), mode: Mode = Mode.online):
    return {
        "uuid_version": event_id.version,
        "weekday": day.strftime("%A"),
        "aware": at is not None and at.tzinfo is not None,
        "urgent": urgent,
        "price_type": type(price).__name__,
        "minutes": length.total_seconds() / 60,
        "mode": mode,
        "price": price,
        "day": day,
    }


c = TestClient(app)
uid = "12345678-1234-4234-8234-123456789abc"
r = c.get(f"/events/{uid}", params={"day": "2026-12-04", "at": "2026-12-04T10:30:00+05:30", "urgent": "yes",
                                    "price": "199.90", "length": "PT90M", "mode": "campus"})
print(r.json())
print(c.get(f"/events/{uid}", params={"day": "2026-12-04", "urgent": "off"}).json()["urgent"])
for bad in ({"day": "04-12-2026"}, {"day": "2026-12-04", "urgent": "maybe"}):
    err = c.get(f"/events/{uid}", params=bad).json()["detail"][0]
    print(err["loc"], err["type"])
print(c.get("/price").text)
print(c.get("/events/not-a-uuid", params={"day": "2026-12-04"}).json()["detail"][0]["type"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'uuid_version': 4, 'weekday': 'Friday', 'aware': True, 'urgent': True, 'price_type': 'Decimal', 'minutes': 90.0, 'mode': 'campus', 'price': 199.9, 'day': '2026-12-04'} False ['query', 'day'] date_from_datetime_parsing ['query', 'urgent'] bool_parsing {"amount":"199.90"} uuid_parsing

Key points

  • Type hints drive parsing, validation and docs
  • bool accepts true/false/1/0/yes/no/on/off
  • datetime with an offset is aware; without it is naive
  • Decimal for money; a response model keeps it exact as a string
  • Invalid values give 422 before your code runs

Common mistakes

  • Using float for money, or returning Decimal values without a response model so they become floats
  • Comparing naive and aware datetimes
  • Accepting ISO strings without offsets and assuming a time zone
  • Using unions of overlapping scalar types such as int | str
  • Doing manual parsing that duplicates what the signature already does

Follow-ups

  • How do you accept a custom date format?
  • How do you validate time zones?
  • What does smart union mode do?

Tips

  • Give 5 types and their accepted inputs
  • Mention naive vs aware
  • Mention Decimal for money