I'm trying to return a dictionary in FastAPI. I've scoured their site and can't find anything that works. Maybe I'm going about this completely wrong but I would imagine I could pass it a dictionary of results and it would return them as structured in the dictionary? The end goal is to pull this information out of a database but for simplicity and testing I've narrowed it down to this.
from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: float = 10.5
tags: List[str] = []
class Items(BaseModel):
items: List[Item]
itemslist = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
@app.get("/items", response_model=Items, response_model_exclude_unset=True)
async def read_item(Items: dict):
return Items(items=itemslist)
When I open the page I get
{
"detail": [
{
"loc": [
"body"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
In the console log I see
127.0.0.1:53845 - "GET /items HTTP/1.1" 422 Unprocessable Entity