Skip to content

Instantly share code, notes, and snippets.

@timothypage
Created June 4, 2023 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timothypage/94ab5979c01c4cc78da5f12458e9fb3a to your computer and use it in GitHub Desktop.
Save timothypage/94ab5979c01c4cc78da5f12458e9fb3a to your computer and use it in GitHub Desktop.
# pip install fastapi "uvicorn[standard]" numpy matplotlib cairocffi
# run with uvicorn index:app (--reload)
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import io
from io import BytesIO
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
# brew install cairo OR apt install libcairo2-dev
# pip install cairocffi (or pycairo, if that floats your boat)
matplotlib.use('Cairo')
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/plot.png")
def get_plot():
image_buffer = BytesIO()
x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.savefig(image_buffer, format="png")
plt.close()
image_buffer.seek(0)
return StreamingResponse(image_buffer, media_type="image/png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment