From 01974ecaa9147adf65640a35eaa7d3e4fd7e69ba Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 16:19:41 +0100 Subject: [PATCH] Add Book schema --- schemas/book.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 schemas/book.py diff --git a/schemas/book.py b/schemas/book.py new file mode 100644 index 0000000..126a026 --- /dev/null +++ b/schemas/book.py @@ -0,0 +1,42 @@ +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. \ No newline at end of file