Read operations
Read Operations
Fetch a single book
Try to create an API endpoint to fetch book based on id.
Code:
from fastapi import FastAPI, Body
from books3 import Book
from datavalidatorhelper import BookRequest
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
""" post request without any input validation
@app.post("/create_book")
async def create_book(book_request=Body()):
BOOKS.append(book_request)
"""
# API endpoint to fetch book by using id
@app.get("/books/{book_id}")
async def read_book_by_id(book_id: int):
for book in BOOKS:
if book.id == book_id:
return book
return {"message": "book not found"}
#post request with input validator
@app.post("/creat_book")
async def create_book(book_request: BookRequest):
new_book = Book(**book_request.model_dump()) # new_book = Book(**book_request.dict()) -> if you are using pydantic version 1 else the model_dump() for pydentic version 2.
# BOOKS.append(new_book) -> it will store the valid input dump but you can have duplicate ids.
BOOKS.append(find_book_id(new_book)) # It will add latest id sequence number to id automatically and will overwrite the provided input so you don't need to bother about the id value sequence.
def find_book_id(book: Book):
if len(BOOKS) > 0:
book.id = BOOKS[-1].id + 1
else:
book.id = 1
return book
Result:
Books selection on basis of rating
We have to take care that order matters and if path is same then path parameter dynamic will shadow static path parameter API endpoint and query parameter will shadow static path end point.
Preference:
dynamic path parameter > static path parameter
query parameter > static path
So it means according to order put static paths first in code as code will be read from top to bottom.
code:
from fastapi import FastAPI, Body
from books3 import Book
from datavalidatorhelper import BookRequest
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
""" post request without any input validation
@app.post("/create_book")
async def create_book(book_request=Body()):
BOOKS.append(book_request)
"""
# API endpoint to fetch book by using id
@app.get("/books/{book_id}")
async def read_book_by_id(book_id: int):
for book in BOOKS:
if book.id == book_id:
return book
return {"message": "book not found"}
# API endpoint to fetch books by rating
@app.get("/books/")
async def read_book_by_rating(rating: int):
book_to_return = []
for book in BOOKS:
if book.rating == rating:
book_to_return.append(book)
return book_to_return
#post request with input validator
@app.post("/creat_book")
async def create_book(book_request: BookRequest):
new_book = Book(**book_request.model_dump()) # new_book = Book(**book_request.dict()) -> if you are using pydantic version 1 else the model_dump() for pydentic version 2.
# BOOKS.append(new_book) -> it will store the valid input dump but you can have duplicate ids.
BOOKS.append(find_book_id(new_book)) # It will add latest id sequence number to id automatically and will overwrite the provided input so you don't need to bother about the id value sequence.
def find_book_id(book: Book):
if len(BOOKS) > 0:
book.id = BOOKS[-1].id + 1
else:
book.id = 1
return book
Result:



Comments
Post a Comment