1

Below is my React code to retrieve the .csv file. I would like the file to be downloaded immediately on click of the button:

downloadData = () => {
    fetch('http://localhost:8000/genreport')
        .then(response => {
            response.blob().then(blob => {
                let url = window.URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = url;
                a.download = 'onomonitoring.csv';
                a.click();
            });
... 
    render() {
        return (
            <div id="container">
                <button onClick={this.downloadData}>Download</button>
            </div>
        )
    }

}

This is my FastAPI code to generate the .csv file:

@app.post("/genreport")
def gen_colreport(db: Session = Depends(get_db)):
    df = collection_report(db)
    date_today = datetime.today().strftime('%Y%m%d')
    col_report_str = "collectionreport_"
    filename = col_report_str + date_today + ".csv"
    # col_report = df.to_csv(filename, encoding="utf-8")
    stream = io.StringIO()
    df.to_csv(stream, encoding="utf-8", index= False)
    response = StreamingResponse(iter([stream.getvalue()]),
                            media_type="text/csv"
       )
    response.headers["Content-Disposition"] = "attachment; filename=%s" % (filename)
    return response

I can download the file from FastAPI but when I run the code it throws a 405 Method Not Allowed error. Is there a way I can download the .csv file from FastAPI directly or retrieve the csv file from the database directly?

Chris
  • 18,724
  • 6
  • 46
  • 80
  • Did you mean ``? Because the `downloadData` you're showing is not a class method. – Mike 'Pomax' Kamermans Aug 03 '22 at 16:09
  • 1
    You have defined your endpoint to accept `POST` requests, however, you seem to be sending a `GET` request from your frontend. – Chris Aug 03 '22 at 16:11
  • I would suggest you have a look at the answers [here](https://stackoverflow.com/a/71205127/17865804), [here](https://stackoverflow.com/a/72053557/17865804) and [here](https://stackoverflow.com/a/71193588/17865804), as they will likely help you with your task. – Chris Aug 03 '22 at 16:17

0 Answers0