Santhosh
Santhosh

Reputation: 11824

python fastapi: I want to get a csv file in return

I have create a fastapi end point. I pass some params and i want to get a csv file. How can i do that. The following is the code.

@app.get("/")
async def root(token: str, dbhost: str, port: int, dbname: str ,username: str, passwd: str,table: str):
    con = psycopg2.connect(dbname=dbname, user=username, password=passwd, host=dbhost, port=port)
    cur = con.cursor()
    save = "{}.csv".format(table)
    store = sql.SQL("""COPY {table} TO STDOUT WITH CSV HEADER""").format(table=sql.Identifier(table),)
    ### --> HOW TO write the store into the save <-------
    con.commit()
    cur.close()
    con.close()
    return csv file ### <- how to return csv file

Upvotes: 3

Views: 6185

Answers (2)

Tomasz Zielański
Tomasz Zielański

Reputation: 473

To return text as a file (e.g. csv):

...
text: str = ...
return StreamingResponse(
    iter([text]),
    media_type='text/csv',
    headers={"Content-Disposition":
             "attachment;filename=<file_name>.csv"})

Bonus for pandas DataFrame:

import pandas as pd

...
df = pd.DataFrame(...)
    
output = df.to_csv(index=False)
return StreamingResponse(
    iter([output]),
    media_type='text/csv',
    headers={"Content-Disposition":
             "attachment;filename=<file_name>.csv"})

Upvotes: 0

Amin Taghikhani
Amin Taghikhani

Reputation: 762

if you have your csv as a binary you can use StreamingResponse like this:

from fastapi.responses import StreamingResponse

...

    export_media_type = 'text/csv'
    export_headers = {
          "Content-Disposition": "attachment; filename={file_name}.csv".format(file_name=file_name)
    }
    return StreamingResponse(csv_file_binary, headers=export_headers, media_type=export_media_type)

if you have your csv as a path you can use FileResponse like this:

from fastapi.responses import FileResponse

...

    return FileResponse(csv_file_path)

Upvotes: 3

Related Questions