A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
example: turn a notebok into api endpoints (#3754)
Myles Scolnick0b41f6b8381a
diff --git a/examples/frameworks/fastapi-endpoint/README.md b/examples/frameworks/fastapi-endpoint/README.mdnew file mode 100644index 0000000000..cde343cdac--- /dev/null+++ b/examples/frameworks/fastapi-endpoint/README.md@@ -0,0 +1,11 @@+# FastAPI + marimo, as an API endpoint++This is a simple example of how to use FastAPI with marimo. This example turns marimo notebooks into an API endpoint, which can be embedded in any FastAPI app.++- Turning functions defined in a notebook into an API endpoint+- Overriding global variables and returning cell outputs++## Running the app++1. [Install `uv`](https://github.com/astral-sh/uv/?tab=readme-ov-file#installation)+2. Run the app with `uv run --no-project main.py`diff --git a/examples/frameworks/fastapi-endpoint/main.py b/examples/frameworks/fastapi-endpoint/main.pynew file mode 100644index 0000000000..b26f971920--- /dev/null+++ b/examples/frameworks/fastapi-endpoint/main.py@@ -0,0 +1,103 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "fastapi",+# "marimo",+# "starlette",+# "matplotlib==3.10.0",+# "pillow==11.1.0",+# ]+# ///+from fastapi import FastAPI, Request+import logging++from fastapi.responses import HTMLResponse, StreamingResponse++# Set up logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++# Create a FastAPI app+app = FastAPI()++[email protected]("/add/{a}/{b}")+async def add_endpoint(request: Request, a: int, b: int) -> int:+ from notebook import add++ # We grab the function from the definition+ # and call it with the a and b arguments+ output, defs = add.run()+ return defs["add"](a, b)++[email protected]("/greet")+async def greet(request: Request):+ from notebook import greet++ name = request.query_params.get("name")++ # We grab the function from the definition+ # and call it with the name argument+ output, defs = greet.run()+ return defs["greet"](name)++[email protected]("/plot")+async def plot(request: Request):+ from notebook import plot+ import json+ from PIL import Image+ import io++ try:+ data = json.loads(request.query_params.get("data"))+ except Exception as e:+ data = {+ "2019": 150,+ "2020": 200,+ "2021": 180,+ "2022": 250,+ "2023": 300,+ }++ # Get the image from the notebook,+ # which is the output of the plot function+ output: Image.Image+ # We override the plot_data argument+ # to use the data passed in the query string+ output, defs = plot.run(plot_data=data)++ # Save the image to a BytesIO object+ buf = io.BytesIO()+ output.save(buf, format="PNG")+ buf.seek(0)++ # Return the image as a StreamingResponse+ return StreamingResponse(+ content=buf,+ media_type="image/png",+ )++[email protected]("/")+async def home(request: Request):+ return HTMLResponse(+ """+ This example shows how to use marimo notebooks as API endpoints in a FastAPI app.++ Try these endpoints:+ <ul>+ <li><a target="_blank" href="/add/1/2">Add two numbers: /add/1/2</a></li>+ <li><a target="_blank" href="/greet?name=World">Get a greeting: /greet?name=World</a></li>+ <li><a target="_blank" href="/plot?data=%7B%222019%22%3A%20150%2C%20%222020%22%3A%20200%2C%20%222021%22%3A%20180%2C%20%222022%22%3A%20250%2C%20%222023%22%3A%20300%7D">Plot a dictionary: /plot?data=%7B%222019%22%3A%20150%2C%20%222020%22%3A%20200%2C%20%222021%22%3A%20180%2C%20%222022%22%3A%20250%2C%20%222023%22%3A%20300%7D</a></li>+ </ul>+ """+ )+++# Run the server+if __name__ == "__main__":+ import uvicorn++ uvicorn.run(app, host="localhost", port=8000, log_level="info")diff --git a/examples/frameworks/fastapi-endpoint/notebook.py b/examples/frameworks/fastapi-endpoint/notebook.pynew file mode 100644index 0000000000..3d557daf51--- /dev/null+++ b/examples/frameworks/fastapi-endpoint/notebook.py@@ -0,0 +1,133 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "marimo",+# "matplotlib==3.10.0",+# "pillow==11.1.0",+# ]+# ///++import marimo++__generated_with = "0.11.2"+app = marimo.App()+++def add():+ def add(a: int, b: int) -> int:+ """Add two numbers together"""+ return a + b++ return (add,)+++def greet():+ def greet(name: str) -> str:+ """Return a greeting message"""+ return f"Hello {name}!"++ return (greet,)+++def fibonacci():+ def fibonacci(n: int) -> list[int]:+ """Return first n numbers of Fibonacci sequence"""+ if n <= 0:+ return []+ elif n == 1:+ return [0]++ sequence = [0, 1]+ while len(sequence) < n:+ sequence.append(sequence[-1] + sequence[-2])+ return sequence++ return (fibonacci,)+++def _():+ import matplotlib.pyplot as plt+ from PIL import Image++ return Image, plt+++def plot(Image, plot_data, plt):+ def plot_dictionary(data: dict) -> None:+ """Plot dictionary items as a bar chart"""+ # Clear any existing plots+ plt.clf()++ # Create figure with higher DPI+ fig = plt.figure(figsize=(10, 6), dpi=100)+ plt.bar(list(data.keys()), list(data.values()))+ plt.xticks(rotation=45)+ plt.xlabel("Items")+ plt.ylabel("Values")+ plt.title("Dictionary Items Plot")+ plt.tight_layout()++ # Convert to PIL Image with proper size preservation+ canvas = fig.canvas+ canvas.draw()+ width, height = fig.get_size_inches() * fig.get_dpi()+ image = Image.frombytes(+ "RGBA", (int(width), int(height)), canvas.buffer_rgba()+ )+ plt.close(fig) # Clean up+ return image++ plot_dictionary(plot_data)+ return (plot_dictionary,)++[email protected](hide_code=True)+def _():+ # Fallback data+ plot_data = {+ "2019": 150,+ "2020": 200,+ "2021": 180,+ "2022": 250,+ "2023": 300,+ }+ return (plot_data,)++[email protected](hide_code=True)+def _(plot_dictionary):+ # Example usage of plot_dictionary+ sample_data = {+ "Apple": 30,+ "Banana": 25,+ "Orange": 40,+ "Mango": 15,+ "Grapes": 35,+ }++ plot_dictionary(sample_data)+ return (sample_data,)+++def stats():+ def stats(numbers: list[float]) -> dict:+ """Calculate basic statistics for a list of numbers"""+ if not numbers:+ return {"mean": None, "min": None, "max": None}+ return {+ "mean": sum(numbers) / len(numbers),+ "min": min(numbers),+ "max": max(numbers),+ }++ return (stats,)+++if __name__ == "__main__":+ app.run()