FastAPI’s native Pydantic integration makes UUID validation automatic — declare uuid.UUID as a type hint and all parsing, validation, and OpenAPI schema generation follow. This guide covers UUID v7 in async SQLAlchemy models, Pydantic v2 schemas, and FastAPI route handlers. See UUID in Python for the broader Python ecosystem context.
Pydantic v2 schema with UUID v7
from pydantic import BaseModel
import uuid
class OrderCreate(BaseModel):
customer_id: uuid.UUID # validates any version
class OrderResponse(BaseModel):
id: uuid.UUID
customer_id: uuid.UUID
status: str
model_config = {'from_attributes': True}
Pydantic v2 validates uuid.UUID from strings, bytes, or UUID objects. Any RFC 9562 version is accepted — UUID v4 and v7 both pass. The OpenAPI spec generated by FastAPI uses format: uuid automatically for uuid.UUID fields. See UUID in OpenAPI.
FastAPI route with UUID path parameter
from fastapi import FastAPI, HTTPException
import uuid
app = FastAPI()
@app.get('/orders/{order_id}', response_model=OrderResponse)
async def get_order(order_id: uuid.UUID):
# FastAPI validates format; returns 422 if invalid
order = await db.get_order(str(order_id))
if not order:
raise HTTPException(status_code=404, detail='Order not found')
return order
@app.post('/orders', response_model=OrderResponse, status_code=201)
async def create_order(body: OrderCreate):
order_id = uuid.uuid7() # Python 3.13+
order = await db.create_order(id=str(order_id), customer_id=str(body.customer_id))
return order
order_id: uuid.UUID in the function signature is all that is needed — FastAPI parses and validates the path segment automatically.
Async SQLAlchemy 2.x
from sqlalchemy import Column, text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
import uuid
engine = create_async_engine('postgresql+asyncpg://user:pw@localhost/db')
class Base(DeclarativeBase):
pass
class Order(Base):
__tablename__ = 'orders'
id = Column(
UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid7, # Python 3.13+ app-layer generation
server_default=text('uuidv7()'), # PostgreSQL 18 DB-layer generation
)
status = Column(str, nullable=False)
async def create_order(session: AsyncSession, status: str) -> Order:
order = Order(status=status) # id assigned by default=uuid.uuid7
session.add(order)
await session.commit()
return order
server_default=text('uuidv7()') requires PostgreSQL 18. On earlier versions, remove server_default — the default=uuid.uuid7 callable handles app-layer generation. See PostgreSQL 18 Ships Native UUID v7.
Dependency injection for UUID generation
from fastapi import Depends
import uuid
def new_uuid() -> uuid.UUID:
"""Injectable UUID v7 factory — swap for uuid.uuid4() in tests."""
return uuid.uuid7()
@app.post('/orders')
async def create_order(
body: OrderCreate,
order_id: uuid.UUID = Depends(new_uuid),
):
return await db.create_order(id=str(order_id), **body.model_dump())
Using Depends for UUID generation makes handlers testable — inject a fixed UUID in tests without patching globals. See UUID Testing Strategies.
Further reading
- UUID in Python — full guide
- Python 3.13 adds uuid.uuid7()
- UUID in Databases
- UUID v7 ORM Support in 2026
- UUID in OpenAPI
- UUID Testing Strategies
External references
- FastAPI path parameters documentation
- Pydantic v2 UUID type
- uuid6 backport for Python 3.9–3.12
- RFC 9562 — UUID standard
Frequently asked questions
How does FastAPI validate UUID path parameters?
FastAPI uses Pydantic for request validation. Declare a path parameter as type uuid.UUID and FastAPI automatically validates the format and returns a 422 error for invalid UUIDs — no additional pipe or decorator needed. The uuid.UUID type accepts any RFC 9562 version (v4, v7, etc.). See UUID in Python for the broader Pydantic v2 pattern.
How do I generate UUID v7 in FastAPI with Python 3.13?
Python 3.13 added uuid.uuid7() to the standard library. Use it as a SQLAlchemy column default: Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid7). For Python 3.9–3.12, install the uuid6 package and use uuid6.uuid7. See Python 3.13 adds uuid.uuid7().