I’m trying to upload a file along with some credential information that I will save as JSON in the database. I’m using form data to send both the file and credentials. However, I need the credentials to be a dictionary with str
type keys and Any
type values. Here is the code written in FastAPI:
@router.post('/upload', response_model=SuccessResponse)
async def upload(file: UploadFile = File(...), credential: Dict[str, Any] = Form(...)):
return response.success(SuccessResponse(data=credential))
Below is the cURL example I’m trying to use:
curl --location '127.0.0.1:8000/api/v1/file/upload'
--form 'file=@"/Users/hanie/Desktop/example.jpg"'
--form 'credential[user_id]="2"'
--form 'credential[page_id]="1"'
However, I keep encountering an error indicating that the credentials are missing:
{"detail": [
{
"type": "missing",
"loc": [
"body",
"credential"
],
"msg": "Field required",
"input": null
}
]}
I thought about adding a dependency to the credential field and parsing it with a function like this:
async def parse_dict_form(request: Request) -> Dict[str, Any]:
form_data = await request.form()
result = {}
prefix_with_brackets = "credential["
for key, value in form_data.items():
if key.startswith(prefix_with_brackets) and key.endswith(']'):
actual_key = key[len(prefix_with_brackets):-1]
result[actual_key] = value
return result
@router.post('/upload', response_model=SuccessResponse)
async def upload(
file: UploadFile = File(...),
credential: Dict[str, Any] = Depends(parse_dict_form)
):
return response.success(SuccessResponse(data=credential))
This solution works, but it causes issues with the documentation, as it doesn’t correctly identify the credential field.
Documentation before adding the dependency:
Documentation after adding the dependency:
What is the best way to resolve this issue?