5

I have this very simple code that gets a dictionary as imput and returns back a dictionary as well:

app = FastAPI()

class User(BaseModel):
    user_name: dict


@app.post("/")
def main(user: User):
   ## some processing
   return user

I'm calling this with the following python code:

import requests
import json 
import pandas as pd

df = pd.read_csv("myfile.csv")
data = {}
data["user_name"] = df.to_dict()
headers = {'content-type': 'application/json'}
url = 'http://localhost:8000/'
resp = requests.post(url,data=json.dumps(data), headers=headers )
resp

Now, I want to do something similar but instead of sending the data with a request from python I want to upload a local file send it to the API and get a processed .csv file back.

Now I have the following code to upload a file:

from typing import Optional
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile
from pydantic import BaseModel
from typing import List
from fastapi.responses import HTMLResponse


app = FastAPI()

class User(BaseModel):
    user_name: dict

@app.post("/files/")
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}


@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}


@app.get("/")
async def main():
    content = """
<body>
<form action="/files/" enctype="multipart/form-data" method="post">
<input name="files" type="file" multiple>
<input type="submit">
</form>
</body>
    """
    return HTMLResponse(content=content)

enter image description here

This allows me to select and load a file: enter image description here

But when I click on send, I'm redirected to: http://localhost:8000/uploadfiles/ and get the following error:

{"detail":"Method Not Allowed"}

How can I send the file for procesing to the API and get a file back as a response?

2
  • how did you read the data from files or upload files? the request will return an obkect, how did you transform it to dataframe? Commented Nov 20, 2020 at 15:26
  • Related answers can be found here, as well as here and here Commented Apr 25, 2023 at 6:01

1 Answer 1

4

I copied your code and I got the same error. After going through the FastAPI documentation for requesting files, it is mentioned that

To receive uploaded files, first install python-multipart.

E.g. pip install python-multipart.

This is because uploaded files are sent as "form data".

After installing the library python-multipart, the code worked perfectly.

References:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.