You can download this code by clicking the button below.
This code is now available for download.
This code defines a FastAPI application that contains a POST endpoint for calculating the discounted price of an item. The user needs to provide the item's name and price, as well as the discount rate.
Technology Stack : FastAPI, Pydantic
Code Type : FastAPI API Endpoint
Code Difficulty : Intermediate
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import random
class Item(BaseModel):
name: str
price: float
app = FastAPI()
def calculate_discounted_price(item: Item, discount_rate: float = 0.1):
# Calculate the discounted price of an item
return item.price * (1 - discount_rate)
@app.post("/calculate_discount/")
async def calculate_discount(item: Item, discount_rate: float = 0.1):
try:
discounted_price = calculate_discounted_price(item, discount_rate)
return {"item": item.name, "original_price": item.price, "discounted_price": discounted_price}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))