FastAPI POST - Error 422 detail'': ( ( loc'':(body file msg'':field required'', type'': value_error missing))) [duplicate]
Asked Answered
C

2

8

I want to read in backend this xlsx file. When I use the swagger I get it, but when I test in frontend I receive an Error 422 - devtools/Network detail'': ( ( loc'':(body file msg'':field required'', type'': value_error missing))).

router = APIRouter()

@router.post('/')
async def upload_file(file: Uploadfile = File(...)):

  try:
    arquivo = await file.read()
    df_cambio = pd.read_excel(arquivo)
    cambio_dict = df_cambio.to_dict('index')
    
    print(cambio_dict)
    return{"file_name": file.filename}
  
  except Exception as e:
    exception_handler(e)

react ->

export defaut function Dropzone() {
const [create, {isLoading}] = usePost();

const handleSubmit = (res) => {
    create('cambios', { data:res.file }})
};
if (isLoading) { return <LoadingPageSkeleton />;}

return (

<BasicForm
  initialValues={{}}
  onSubmit={handleSubmit}
>
    <FormInput id="file />
    <FormSubmitButton/>
</Basicform>
Cabana answered 11/8, 2022 at 20:42 Comment(3)
UploadFile requires that you send a form with enctype="multipart/form-data and an input type="file" field. Since you haven't included what create does, I'm guessing that it submits the content as JSON and not as a multipart form post. If you want to submit a JSON body (as is common from a Javascript application such as react), you can instead use a pydantic model that matches your JSON strucuture and encode the file data as base64 data, which you deserialize on the server side.Lodgings
You would need to send the file data as FormData, using the key defined in your endpoint, i.e., file, and the file object obtained from an <input type="file"> element. For instance, var formData = new FormData(); formData.append("file", fileInput.files[0]);. Please have a look at the answers here, as well as here and here, for more details.Jarrell
You may find this answer helpful as well.Jarrell
S
3

I faced similar issue by trying to create python pop request for FastAPI demo file upload. Working from docs where it gave me ready code in form of curl line:

curl -X 'POST' \
  'http://127.0.0.1:8000/uploadfile/' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@test_file'

(FastAPI auto generated docs page). Which i used as hint and from which I got that header for file name should be in the form of "type" : "multipart/form-data" , files = { "file" : test_file_descriptor } And it worked

More exact: key for the file descriptor should be file. My case (Python):

test_response = requests.post(
  test_url, 
  data={
      'filename': test_file ,
      "msg":"hello" ,
      "type" : "multipart/form-data"
    }, 
      files = { "file" : test_file  } 
  ) 

Where test_file` is file descriptor.

I know that my case might be different, but this is the only meaningful google link for this error, and someone with my case could also use it.

Slattery answered 15/8, 2022 at 23:59 Comment(1)
One observation that took me a while to figure out: the fact that the file descriptor in the request should be named file is due to the fact that the argument of the upload_file function is named file. If you change the name of the function argument you can/must change the name of the file descriptor in the request.Helaine
B
0

check the post request you are sending as it's case sensitive .swagger document post part and testing doc post request should match.

And request 
"""{
            "question": "#(question)",
            "History":{}
                   
    }"""    
When method post
Breadbasket answered 27/9, 2023 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.