I'm working on a FastAPI project where I need to receive both JSON data and a file upload in the same request. Specifically, I need to pass an array of integers within the JSON data while also uploading a file. Here is what my request body looks like:
- title (string)
- description (string)
- comments (string)
- due_date (date)
- priority (string)
- assigned_to (array of integers)
- file (file upload)
I'm having trouble getting FastAPI to accept this type of mixed data in a single request. Here is my current approach:
from fastapi import FastAPI, File, UploadFile, Formfrom pydantic import BaseModelfrom typing import Listimport datetimeapp = FastAPI()class TaskCreate(BaseModel): title: str description: str comments: str due_date: datetime.date priority: str assigned_to: List[int]@app.post("/tasks/")async def create_task( title: str = Form(...), description: str = Form(...), comments: str = Form(...), due_date: datetime.date = Form(...), priority: str = Form(...), assigned_to: List[int] = Form(...), file: UploadFile = File(...)): return {"title": title, "description": description, "comments": comments, "due_date": due_date, "priority": priority, "assigned_to": assigned_to, "file_name": file.filename}
The assigned_to parameter does not seem to accept an array of integers when sent with Form(...). FastAPI throws an error because it does not support lists in form data.
I need a way to send both JSON data (including an array of integers) and a file in the same request and have FastAPI handle it correctly. What is the best approach to achieve this in FastAPI?