FastAPI Item Retrieval Function

  • Share this:

Code introduction


This code defines a FastAPI application within a function named xxx. It creates an instance of a FastAPI application and defines a path operation to retrieve information about a specific item by its ID. If the item does not exist, it returns a 404 error.


Technology Stack : FastAPI, Pydantic

Code Type : FastAPI Web Framework

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 xxx(item_id: int):
    app = FastAPI()
    items = [
        Item(name="Item 1", price=5.99),
        Item(name="Item 2", price=10.99),
        Item(name="Item 3", price=15.99)
    ]
    
    @app.get("/items/{item_id}", response_model=Item)
    def read_item(item_id: int):
        item = next((item for item in items if item.id == item_id), None)
        if item is None:
            raise HTTPException(status_code=404, detail="Item not found")
        return item

    return app