How to post dictionary data type in FastAPI Request Forms ? #6322
-
First Check
Commit to Help
Example Code@menu.post("/add-menu")
async def addmenu(
ItemName: str = Form(...),
ItemShortDesc: str = Form(...),
ItemPrice: str = Form(...),
ItemCategory: list = Form(...),
ItemStatus: str = Form(...),
ItemChoices: list[dict[str,str]] = Form(...)):
return ItemChoicesDescriptionPOST Method using FastAPI Request Form I am trying to do,
I got the below error, error Code:422 "detail": [ How can I use "dict" or "list" of "dict" in FastAPI request form? Please help me out of any possible chance. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.73.0 Python Versionpython3.9 Additional Context |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
|
@growwithsundar , I would suggest using a pydantic model for validating the form: from typing import List, Dict
from fastapi import FastAPI
from fastapi.param_functions import Depends
from pydantic import BaseModel
app = FastAPI()
class CustomForm(BaseModel):
ItemName: str
ItemShortDesc: str
ItemPrice: float
ItemCategory: List[str]
ItemStatus: str
ItemChoices: List[Dict[str, str]]
@app.post("/add-menu")
async def addmenu(form_data: CustomForm = Depends()):
return form_data |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for your time and workaround. When I send request from IOS Swift 5 using application/json request body, FastAPI throws error and I deep searched for solution but I couldn't find one proper solutions. Please help me on this and actually there are many queries regarding this in web and no proper solution for the same. Please help me and people who facing the similar issues. **Sending Data From IOS Swift 5 ** Adding Header value Alamofire API Call Response Error 422 from FastAPI |
Beta Was this translation helpful? Give feedback.
-
|
@growwithsundar, using pydantic is not a workaround, but the preferred way to do this. |
Beta Was this translation helpful? Give feedback.
-
|
@growwithsundar You cannot send the data as a json in form fields. It needs to be sent as a stringified JSON and on the FastAPI side, you need convert this to your desired object. Form fields work okay for simple datatypes. See the link for reference: https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi |
Beta Was this translation helpful? Give feedback.
-
Thanks it worked |
Beta Was this translation helpful? Give feedback.



@growwithsundar You cannot send the data as a json in form fields. It needs to be sent as a stringified JSON and on the FastAPI side, you need convert this to your desired object.
Form fields work okay for simple datatypes.
See the link for reference: https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi