FastAPI Endpoint for Item Creation with Random Price Generation

  • Share this:

Code introduction


This creates a FastAPI endpoint to receive an item information and randomly generate a price for it.


Technology Stack : FastAPI, Pydantic, random

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()

@app.post("/items/")
def create_item(item: Item):
    # Generate a random price for the item
    item.price = random.uniform(1.0, 100.0)
    return item