I am using method POST
to upload one file through Postman and save it to my local directory. However, a 422(Unprocessable entity) occurs, as shown below:
I selected the file as binary and uploaded it on Postman, as you can see in the posted image.
Below is how my FastAPI backend looks like:
main.py
from fastapi import FastAPI
from api.endpoints.vendor import router
app = FastAPI(title='Vendor Acknolegment API')
app.include_router(router, prefix='/vendor', tags=['vendor confirmation'])
if __name__ == '__main__':
import uvicorn
print("entered here")
uvicorn.run("main:app", host="0.0.0.0", port=8000,
log_level='info', reload=True)
vendor.py
from fastapi import APIRouter, status, File, UploadFile
#from lxml import etree
import os
# file path
UPLOAD_DIR = r"c:ack"
# check if the directory exists.
os.makedirs(UPLOAD_DIR, exist_ok=True)
# creates the endpoint path
router = APIRouter()
# POST Ack
@router.post("/ack/", status_code=status.HTTP_201_CREATED)
async def upload_ack(file: UploadFile = File(...)):
# define the complete path where the file will be saved.
file_location = os.path.join(UPLOAD_DIR, file.filename)
with open(file_location, "wb") as f:
f.write(await file.read())
return {"message": f"The file '{file.filename}' has been successfully saved into the server."}
Diego Rezende is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
As described in this answer, and demonstrated in this answer as well, when using UploadFile
, the file(s) are uploaded as multipart/form-data
. Hence, in Postman, you should rather go to Body
-> form-data
and enter the key name given for the UploadFile
parameter in your API endpoint—in your case, that is file
, since you defined it as file: UploadFile = File(...)
—and upload your file in the value
section.
If you instead would like to use the binary
option in Postman to upload files, then please check this answer (see the Update section) and this answer on how you should have the API endpoint implemented in your backend.
2