FastAPI Item Creation Endpoint

  • Share this:

Code introduction


This code defines a FastAPI application that includes an API endpoint for creating items. The endpoint accepts an Item object, generates a random ID, simulates storing the item in a database, and returns the item ID and item details.


Technology Stack : FastAPI, Pydantic, Random

Code Type : FastAPI API Function

Code Difficulty : Intermediate


                
                    
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import random

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

def create_item(app: FastAPI, item: Item):
    # Generate a random item ID
    item_id = random.randint(1, 1000)
    # Simulate storing the item in a database
    app.state.items[item_id] = item
    return {"item_id": item_id, "item": item.dict()}

app = FastAPI()

app.state.items = {}

@app.post("/items/")
async def create_item_endpoint(item: Item):
    return create_item(app, item)