From 96d52b2f03ffaf6cf43f62a5ab49bce438fdb5c9 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 17:28:22 +0100 Subject: [PATCH] Add Book schema --- schemas/book.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 schemas/book.py diff --git a/schemas/book.py b/schemas/book.py new file mode 100644 index 0000000..d76cc3b --- /dev/null +++ b/schemas/book.py @@ -0,0 +1,43 @@ +from pydantic import BaseModel, Field +from uuid import UUID + +# Base schema for Book +class BookBase(BaseModel): + title: str = Field(..., description="Book title") + author: str = Field(..., description="Author name") + description: str | None = Field(None, description="Book description") + author_id: UUID = Field(..., description="Author ID") + + class Config: + schema_extra = { + "example": { + "title": "The Great Gatsby", + "author": "F. Scott Fitzgerald", + "description": "A classic American novel about the Roaring Twenties.", + "author_id": "a7d93b0e-8c6d-4d1a-9e9c-b0e9d8c8d9f3" + } + } + +# Schema for creating a new Book +class BookCreate(BookBase): + pass + +# Schema for Book responses +class Book(BookBase): + id: UUID = Field(..., description="Book ID") + + class Config: + orm_mode = True +``` + +This code defines three Pydantic schemas for the Book entity: + +1. `BookBase`: A base schema that includes the common fields for the Book entity. +2. `BookCreate`: A schema that inherits from `BookBase` and is used for creating a new Book (e.g., in a POST request). +3. `Book`: A schema that inherits from `BookBase` and includes an additional `id` field, which is typically used for API responses. + +The `Field` class is used to add validation and metadata to the fields. For example, the `title` and `author` fields are required, while the `description` field is optional. The `author_id` field is a UUID, and the `id` field in the `Book` schema is also a UUID. + +The `Config` class is used to provide additional configuration options, such as including example values for the fields. + +Note that this code assumes that you have installed the `pydantic` library and imported the necessary modules (`BaseModel`, `Field`, and `UUID`). \ No newline at end of file