0

I have an endpoint that accepts a file and some JSON data that describes the file. When I create the endpoint, everything I try results in the error:

"msg": "value is not a valid dict",
"type": "type_error.dict"

An minimal reproducable example of this is:

from fastapi import FastAPI, File
from fastapi.testclient import TestClient
import uvicorn
from pydantic import BaseModel
import json

class TestEndpointModel(BaseModel):
    age: int


app = FastAPI()

@app.post("/")
def test_endpoint(data: TestEndpointModel, name: str = File(...)):
    return "hi"

client = TestClient(app)
response = client.post(
    "/",
    files={
        "data": json.dumps({"age": 21}).encode('ascii'),
        "name": "tom".encode('ascii')
    }
)

print(f"{response.status_code=}, {response.json()=}")

uvicorn.run(app)

This prints:

response.status_code=422, response.json()={'detail': [{'loc': ['body', 'data'], 'msg': 'value is not a valid dict', 'type': 'type_error.dict'}, {'loc': ['body', 'name'], 'msg': 'str type expected', 'type': 'type_error.str'}]}

and then when you use the Swagger UI docs, you get the same error:

Swagger UI

How do I fix this error?

Tom McLean
  • 2,254
  • 1
  • 2
  • 21

0 Answers0