Pydantic v1 vs Pydantic v2 | code for Book class and it's object

 Pydantic v1 vs Pydantic v2

FastAPI is now compatible with both Pydantic v1 and Pydantic v2.
You need to take care of methods name changes according to usage of Pydantic.

Three of them are:

  • .dict() function is now renamed to .model_dump()
  • schema_extra frunction within a Config class is now renamed to json_schema_extra
  • Optional variables need a =None example: id: Optional[int]=None

Code and result: Get request code

books3.py
class Book:
    id: int
    title: str
    author: str
    description: str
    rating: int

    def __init__(self, id: int, title: str, author: str, description: str, rating: int):
        self.id = id
        self.title = title
        self.author = author
        self.description = description
        self.rating = rating

main.py
from fastapi import FastAPI
from books3 import Book

app = FastAPI()

BOOKS = [
    Book(id=1, title="DSA with Java", author="Puneet Kumar Singh", description="A comprehensive guide to Data Structures and Algorithms using Java.", rating=5),
    Book(id=2, title="Python Programming", author="Puneet Kumar Singh", description="An introduction to Python programming for beginners.", rating=4),
    Book(id=3, title="Machine Learning Basics", author="Puneet Kumar Singh", description="Understanding the fundamentals of Machine Learning.", rating=4),
    Book(id=4, title="Web Development with FastAPI", author="Ramesh Jha", description="Building web applications using FastAPI.", rating=3),
    Book(id=5, title="Data Science with Python", author="Kalidas", description="A guide to Data Science using Python.", rating=2),
    Book(id=6, title="Advanced Java Programming", author="Kalpana Gupta", description="Deep dive into advanced concepts of Java programming.", rating=1)
]

@app.get("/books/") # static path to get all books
async def read_all_books():
    """
    This function returns the list of all books.
    """
    return BOOKS

Result:




Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment