Send a csv file to fastAPI and get a new file back

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?

Upvotes: 5

Views: 9107

Answers (1)

Gambit1614
Gambit1614

Reputation: 8811

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:

Upvotes: 4

Related Questions