Pydantic Schemas
So far, most of the work has been building up and structuring the base project, moving forward, in this guide, we'll get into the fundamental coding aspect of FastAPI. The example will begin with APIs for a blog application and transition into serving HTML responses.
Introducing basic Pydantic schema types here, but there are many more specific types as documented here:
https://docs.pydantic.dev/1.10/
Remember since starting this project Pydantic Version 2 has been released, for now I'm sticking with v1 and will either update at a later date or publish a whole new v2 version of this content, but I need SQLModel to catch up! As always, these the world of software development is a moving target.
Pydantic deals with incoming data validation. However, in conjunction with SQLModel, they will also serve as a means for managing the corresponding database tables.
Once again, as the project grows, it's a good idea to keep things structured. Therefore, create a subdirectory for schemas:
There will be three core Pydantic schemas, one for what values are needed as
input by the API for a given record, another that provides a response output
that will include things like an id
and created_date
in this case. The third is
specifically for interacting with the database and includes table=True
.
Add the following:
import uuid
import datetime
from pydantic.types import UUID
from sqlmodel import SQLModel, Field
# Posts Schemas
class BlogPostIn(SQLModel):
title: str
content: str
cover_image: str
published: bool
class Config:
json_schema_extra = {
"example": {
"title": "Lorem ipsum",
"content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"cover_image": "http://www.exampleforyou.net/static/img/excepteur_sint.jpg",
"published": True
}
}
class BlogPostOut(BlogPostIn):
id: uuid.UUID
created_date: datetime.datetime
# SQLModel Database Schemas
class BlogPost(BlogPostIn, table=True):
id: UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
index=True,
nullable=False)
created_date: datetime.datetime | None = Field(
default_factory=datetime.datetime.utcnow,
nullable=False)