FastAPI Item Creation with Pydantic Validation

  • Share this:

Code introduction


This code defines a FastAPI application that can create a new item. It uses Pydantic to validate and parse request data and returns a 400 error if the price is less than or equal to 0.


Technology Stack : FastAPI, Pydantic

Code Type : Web API

Code Difficulty : Intermediate


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

# Define a Pydantic model for request data
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

# Create a FastAPI instance
app = FastAPI()

# Define a route to create a new item
@app.post("/items/")
async def create_item(item: Item):
    # Check if the item price is less than or equal to 0
    if item.price <= 0:
        raise HTTPException(status_code=400, detail="Price must be greater than 0")
    # Create a new item
    return {"name": item.name, "price": item.price, "description": item.description}

# JSON representation of the code