Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Figure in FastAPI [duplicate]

Im trying to return a matplotlib.figure.Figure in FastAPI. If I save it like an image it works (code here):

@router.get("/graph/{id_file}", name="Return the graph obtained")
async def create_graph(id_file: str):
        data = HAR.createGraph(id_file)
        graph = HAR.scatterplot(data['dateTimes'], data['label'], "Time", "Activity")
        graph.savefig('saved_figure.jpg')
        
        return FileResponse('saved_figure.jpg')

Where graph is my Figure. But I would like to show it without saving in mi computer.

like image 344
a.v. Magia Avatar asked Feb 14 '26 05:02

a.v. Magia


1 Answers

savefig can accept binary file-like object. It can be used to achieve what you want.

The code could be:

from io import BytesIO
from starlette.responses import StreamingResponse
...


@router.get("/graph/{id_file}", name="Return the graph obtained")
async def create_graph(id_file: str):
    data = HAR.createGraph(id_file)
    graph = HAR.scatterplot(data['dateTimes'], data['label'], "Time", "Activity")
    
    # create a buffer to store image data
    buf = BytesIO()
    graph.savefig(buf, format="png")
    buf.seek(0)
        
    return StreamingResponse(buf, media_type="image/png")
like image 98
umat Avatar answered Feb 16 '26 17:02

umat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!