FastAPI Item Creation Endpoint

  • Share this:

Code introduction


This code defines a FastAPI endpoint to create a new item. It uses Pydantic for data validation and SQLAlchemy ORM for database interactions.


Technology Stack : FastAPI, Pydantic, SQLAlchemy

Code Type : FastAPI Endpoint

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):
    # Add an item to the database
    try:
        app.db.add(item)
        app.db.commit()
        return {"message": "Item created successfully", "item": item.dict()}
    except Exception as e:
        app.db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

# Example usage
app = FastAPI()

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