Item Parsing and Creation Function Overview

  • Share this:

Code introduction


This function takes a dictionary containing item information, parses it into an `Item` model, and then calls the `create_item` function to create the item. If there is a validation error during parsing, it raises an HTTP exception.


Technology Stack : FastAPI, Pydantic

Code Type : FastAPI custom function

Code Difficulty : Intermediate


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

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

def create_item(item: Item):
    # Simulate adding an item to a database
    # For demonstration purposes, we'll just return the item
    return item

def get_random_item():
    # Generate a random item with random values for demonstration
    random_name = f"Item{random.randint(1, 100)}"
    random_price = round(random.uniform(10.0, 100.0), 2)
    random_tax = round(random.uniform(0.0, 20.0), 2) if random.choice([True, False]) else None
    return Item(name=random_name, price=random_price, tax=random_tax)

def xxx(item_data: dict):
    try:
        # Try to parse the item data into an Item model
        item = Item(**item_data)
    except ValidationError as e:
        # If there is a validation error, raise an HTTPException
        raise HTTPException(status_code=422, detail=str(e))

    # Create the item using the create_item function
    created_item = create_item(item)
    return created_item

# JSON Explanation