FastAPI Item Creation with Exception Handling

  • Share this:

Code introduction


This function creates an item using FastAPI and Pydantic, handling exceptions that may occur during the item creation process. It accepts a Pydantic model containing item information and returns the created item. If an exception occurs during item creation, it raises an HTTP exception.


Technology Stack : FastAPI, Pydantic

Code Type : FastAPI Function

Code Difficulty : Intermediate


                
                    
import fastapi
from pydantic import BaseModel
from fastapi import HTTPException

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

def create_item(item: Item):
    # This function creates an item in a hypothetical database using FastAPI and Pydantic
    # It also handles exceptions if the item creation fails
    try:
        # Simulating item creation process
        new_item = {
            "name": item.name,
            "description": item.description,
            "price": item.price,
            "tax": item.tax
        }
        # Here you would typically save `new_item` to a database
        # For this example, we'll just return it
        return new_item
    except Exception as e:
        # If something goes wrong during item creation, raise an HTTPException
        raise HTTPException(status_code=500, detail=str(e))