Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

python - How to send file to fastapi endpoint using postman

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 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 fastapi, 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

I tested it with Postman v7.16.1

Let me know if you still have problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...