55 lines
2.2 KiB
Python
55 lines
2.2 KiB
Python
from pydantic import BaseModel, Field
|
|
from typing import Optional
|
|
|
|
# Base Schema
|
|
class BookBase(BaseModel):
|
|
title: str = Field(..., description="Book title")
|
|
description: Optional[str] = Field(None, description="Book description")
|
|
author: str = Field(..., description="Book author")
|
|
pages: int = Field(..., gt=0, description="Number of pages")
|
|
|
|
class Config:
|
|
schema_extra = {
|
|
"example": {
|
|
"title": "The Great Gatsby",
|
|
"description": "A novel about the decadence of the Jazz Age.",
|
|
"author": "F. Scott Fitzgerald",
|
|
"pages": 180
|
|
}
|
|
}
|
|
|
|
# Schema for creating a new Book
|
|
class BookCreate(BookBase):
|
|
user_id: str = Field(..., description="ID of the user creating the book")
|
|
|
|
class Config:
|
|
schema_extra = {
|
|
"example": {
|
|
"title": "The Great Gatsby",
|
|
"description": "A novel about the decadence of the Jazz Age.",
|
|
"author": "F. Scott Fitzgerald",
|
|
"pages": 180,
|
|
"user_id": "user123"
|
|
}
|
|
}
|
|
|
|
# Schema for Book responses
|
|
class Book(BookBase):
|
|
id: int
|
|
user_id: str
|
|
|
|
class Config:
|
|
orm_mode = True
|
|
```
|
|
|
|
This code defines three Pydantic models for the Book entity:
|
|
|
|
1. `BookBase`: A base model that defines the common fields for a book (title, description, author, and pages).
|
|
2. `BookCreate`: A model that inherits from `BookBase` and adds the `user_id` field, which is required for creating a new book.
|
|
3. `Book`: A model that inherits from `BookBase` and adds the `id` and `user_id` fields, which are typically required for API responses.
|
|
|
|
The `Field` class is used to define validation rules and descriptions for each field. For example, the `title` and `author` fields are required, the `pages` field must be a positive integer, and the `description` field is optional.
|
|
|
|
The `Config` class is used to provide additional configuration options for each model, such as example values and ORM mode for API responses.
|
|
|
|
Note that this code assumes that the `user_id` field is a string representing the ID of the user creating the book. If the `user_id` field is a foreign key to the `users` table, you may need to modify the field type accordingly. |