Add Book schema
This commit is contained in:
parent
391540a528
commit
96d52b2f03
43
schemas/book.py
Normal file
43
schemas/book.py
Normal file
@ -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`).
|
Loading…
x
Reference in New Issue
Block a user