Fastapi: [QUESTION]

Created on 21 Aug 2019  路  5Comments  路  Source: tiangolo/fastapi

Is it possible to send a zip file as an attachment in a response? Looked through the starlette's response library but could not figure out a way to do this. My initial feeble attempt at making this work was using the Response object, specificying the media_type as 'application/zip' and passing the zipped I/O buffer in the content...normally in Flask I would do something like:

response_obj = Response(zipped, mimetype='application/zip', headers={
            'Content-Disposition': 'attachment;filename=api.zip'
            })
return response_obj

Where zipped was of type io.BytesIO(). Is something like this possible in FastAPI or using Starlette's responses?

question

Most helpful comment

works in swagger too for more swag
img

All 5 comments

It should be possible using Starlette's responses, but I'm not sure how high-level of an API there is for this. Either way, I think this would almost certainly be making direct (or nearly direct) use of starlette, rather than FastAPI, so you might have more luck asking there.

as I was commenting on https://github.com/encode/starlette/issues/609 it does indeed work with a FileResponse

@router.get("/zip")
def zip():
    content = b"<file content>" * 1000
    with open("/tmp/stuff", "wb") as tozip:
        tozip.write(content)
    with ZipFile('example.zip', 'w') as myzip:
        myzip.write("/tmp/stuff")
    response = FileResponse(path='example.zip', filename="example.zip")
    return response

works in swagger too for more swag
img

Worked like a charm! 馃憣

Thanks @euri10 and @dmontagu ! :clap: :bowing_man:

Thanks @hrtejada for reporting back and closing the issue.

Was this page helpful?
0 / 5 - 0 ratings