How to return both a dict and a file by an endpoint using FastAPI?

48 Views Asked by At

I need to return both a dict and a file using FastAPI. But I can only achieve so far returning a file. Could you please show me how to do it? Thanks.

Expected Usage

Primary usage

The primary usage is that, I will use an external Python app to call this API by (requests.post)

out_data, zip_file = requests.post(url, json={"input_data": "some"})
# And then,
# 1. Save the zip_file to local drive
# 2. Post analysis of the out_data

Nice-to-have usage

As with FastAPI, I can use its built-in docs directly from the web-browser. Like http://127.0.0.1:8000/docs/ --> Try it out --> See the out_data in the response part and download the zipfile directly from the browser.

Example code (not working)

Here is example code that you can please start with.


import os
import shutil
from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel

app = FastAPI()

CUR_DIR = Path(os.path.dirname(__file__))


class OutData(BaseModel):
    name: str
    value: float


@app.post("/", response_class=FileResponse)
async def run(input_data: str) -> tuple[OutData, FileResponse]:  # This type hint gives an Error by FastAPI.
    out_data = OutData(name="A Name", value=10)
    # Here is just make the current folder a zip-file.
    shutil.make_archive(str(CUR_DIR), "zip", str(CUR_DIR))
    zip_file = CUR_DIR.parent.joinpath(f"{CUR_DIR.name}.zip")
    return out_data, FileResponse(path=zip_file, filename=zip_file.name)

0

There are 0 best solutions below