You can download this code by clicking the button below.
This code is now available for download.
This function creates a FastAPI application and defines an endpoint to retrieve item information. It uses Pydantic's BaseModel to define data models and handles not found items using HTTPException.
Technology Stack : FastAPI, Pydantic
Code Type : FastAPI Endpoint
Code Difficulty : Intermediate
import random
def random_fastify_endpoint():
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
id: int
name: str
items = {
1: {"id": 1, "name": "Item1"},
2: {"id": 2, "name": "Item2"}
}
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int):
item = items.get(item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
return app