5

I faced the difficulty of testing api using postman. Through swagger file upload functionality works correctly, I get a saved file on my hard disk. I would like to understand how to do this with the postman. I use the standard way to work with files which I use when working with Django, flask.

Body -> form-data: key=file, value=image.jpeg

But with fast API, I get an error

127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity

main.py

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    img = await file.read()
    if file.content_type not in ['image/jpeg', 'image/png']:
        raise HTTPException(status_code=406, detail="Please upload only .jpeg files")
    async with aiofiles.open(f"{file.filename}", "wb") as f:
        await f.write(img)
    return {"filename": file.filename}

I also tried body -> binary: image.jpeg . But got the same result

postman query

Innat
  • 16,113
  • 6
  • 53
  • 101
Jekson
  • 2,892
  • 8
  • 44
  • 79
  • I'm not at my office desk, but I faced a similar problem once. The solution is to simply add the file to the `FormData` javascript class, and send it. This will directly attach the image to the body of the request. With your`key=file` you are passing multiple parameters (it's an extra one with respect to the `value=image.jpeg`). In any case you can inspect the content of your request via the console of your browser and get inspired – lsabi Jul 08 '20 at 20:35
  • @lsabi Thank you for the feedback, but I'm not sure what I need to do exactly. Maybe you can show me? – Jekson Jul 09 '20 at 07:19

2 Answers2

15

My code:

from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/file/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

Setup in Postman enter image description here

As stated in https://github.com/tiangolo/fastapi/issues/1653, the parameter name for the file is the key value that you have to use. Before you were using key=file and value=image.png (or whatever). Instead, FastAPI accepts file=image.png. Thus the error, since the file is necessary, but it is not present (at least, the key with that name is not present).

P.S. I tested it with Postman v7.16.1

Innat
  • 16,113
  • 6
  • 53
  • 101
lsabi
  • 3,641
  • 1
  • 14
  • 26
1

As mentioned in the response, I could see the key for the file uploaded is missing. Mention the key for the file in body params as file.