2025-03-25 16:19:41 +01:00

42 lines
1.6 KiB
Python

from pydantic import BaseModel, Field
# Base Schema
class BookBase(BaseModel):
title: str = Field(..., description="Title of the book")
author: str = Field(..., description="Author of the book")
description: str = Field(..., description="Description of the book")
published_year: int = Field(..., gt=0, description="Year the book was published")
# Schema for creating a new Book
class BookCreate(BookBase):
isbn: str = Field(..., description="ISBN of the book")
class Config:
schema_extra = {
"example": {
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"description": "A novel about the decadence of the Jazz Age.",
"published_year": 1925,
"isbn": "978-0743273565"
}
}
# Schema for Book responses
class Book(BookBase):
id: int
isbn: str
class Config:
orm_mode = True
```
This code defines three Pydantic schemas for the Book entity:
1. `BookBase`: A base schema containing common fields for Book.
2. `BookCreate`: A schema for creating a new Book, inheriting from `BookBase` and adding the `isbn` field.
3. `Book`: A schema for Book responses, inheriting from `BookBase` and adding the `id` and `isbn` fields.
The `Field` class is used to add validation and descriptions to the fields. For example, `published_year` is validated to be greater than 0, and `isbn` is required for creating a new Book.
The `Config` class is used to provide examples for the `BookCreate` schema and to enable the `orm_mode` for the `Book` schema, which is useful when working with ORMs like SQLAlchemy.