Random Fruit Item Endpoint in FastAPI

  • Share this:

Code introduction


This code defines a FastAPI application with an endpoint that returns a random fruit item.


Technology Stack : FastAPI, Pydantic

Code Type : FastAPI API Endpoint

Code Difficulty : Intermediate


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

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

def get_random_item():
    items = [
        {"name": "Apple", "price": 1.5},
        {"name": "Banana", "price": 0.8},
        {"name": "Cherry", "price": 2.0},
        {"name": "Date", "price": 1.2},
        {"name": "Elderberry", "price": 3.5}
    ]
    return random.choice(items)

@app.get("/random-item/")
async def random_item():
    item = get_random_item()
    return {"name": item["name"], "price": item["price"]}