Post request with parameter as a streamlit file_uploader object for a pdf throws `422 Unprocessable Entity` on FastAPI


I am trying to send a streamlit file_uploader object for a pdf as a post request to a FastAPI based server. However, the server throws 422 Unprocessable Entity error. My server side code looks like the following."/file/upload")
async def upload_file(username: str, uploaded_file: UploadFile = File(...)):
    path_to_save_file = Path.home() / username / "saved_files"
    path_to_save_file.mkdir(parents=True, exist_ok=True)
    file_location = f"{path_to_save_file}/{uploaded_file.filename}"
    with open(file_location, "wb+") as file_object:
    return {"INFO": f"File '{uploaded_file.filename}' saved to your profile."}

Client side code looks the following

uploaded_pdf = st.file_uploader('Upload a file', type="pdf")
url = "http://localhost:8000/file/upload"
if st.button("Upload PDF"):
    payload = {"username": username, "uploaded_file": uploaded_pdf.getvalue()}
    response =, payload)

The relevant API endpoint works correctly with a pdf on http://localhost:8000/docs#. I also tried just passing uploaded_pdf instead of uploaded_pdf.getvalue() but to no avail.

Would appreciate any insight on how to fix it. Thank!!

Found answer to the question. All I did is change the client side code to accept file-based parameters separately through files param. It begun to look like the following.

url = "http://localhost:8000/file/upload"
if st.button("Upload PDF"):
    payload = {"username": username, "filename":}
    response =, params=payload, files={"uploaded_file": uploaded_pdf.getvalue()})

This looks like it’ll only work locally and not across machines. You’d need to send the file byte stream uploaded by the client to the FastAPI endpoint. Specifically, uploaded_file.file references the client machine.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.