Skip to content

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.

examples: refresh fastapi example (#4562)

Dylan Madisettif67d6cfe741c
diff --git a/examples/frameworks/fastapi-endpoint/main.py b/examples/frameworks/fastapi-endpoint/main.py
index b26f971920..061e06c53b 100644
--- a/examples/frameworks/fastapi-endpoint/main.py
+++ b/examples/frameworks/fastapi-endpoint/main.py
@@ -8,6 +8,9 @@
# "pillow==11.1.0",
# ]
# ///
+import marimo
+import fastapi
+
from fastapi import FastAPI, Request
import logging
@@ -27,8 +30,7 @@ async def add_endpoint(request: Request, a: int, b: int) -> int:
# 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)
+ return add(a, b)
@app.get("/greet")
@@ -39,8 +41,7 @@ async def greet(request: Request):
# We grab the function from the definition
# and call it with the name argument
- output, defs = greet.run()
- return defs["greet"](name)
+ return greet(name)
@app.get("/plot")
@@ -66,7 +67,7 @@ async def plot(request: Request):
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)
+ output, _ = plot.run(plot_data=data)
# Save the image to a BytesIO object
buf = io.BytesIO()
@@ -83,8 +84,11 @@ async def plot(request: Request):
@app.get("/")
async def home(request: Request):
return HTMLResponse(
- """
+ f"""
This example shows how to use marimo notebooks as API endpoints in a FastAPI app.
+ <br/>
+ using marimo {marimo.__version__} and fastapi {fastapi.__version__}
+ <br/>
Try these endpoints:
<ul>
diff --git a/examples/frameworks/fastapi-endpoint/notebook.py b/examples/frameworks/fastapi-endpoint/notebook.py
index 3d557daf51..f5513707b7 100644
--- a/examples/frameworks/fastapi-endpoint/notebook.py
+++ b/examples/frameworks/fastapi-endpoint/notebook.py
@@ -9,81 +9,88 @@
import marimo
-__generated_with = "0.11.2"
+__generated_with = "0.12.10"
app = marimo.App()
+with app.setup:
+ import matplotlib.pyplot as plt
+ from PIL import Image
-def add():
- def add(a: int, b: int) -> int:
- """Add two numbers together"""
- return a + b
- return (add,)
+def add(a: int, b: int) -> int:
+ """Add two numbers together"""
+ return a + b
-def greet():
- def greet(name: str) -> str:
- """Return a greeting message"""
- return f"Hello {name}!"
+def greet(name: str) -> str:
+ """Return a greeting message"""
+ return f"Hello {name}!"
- return (greet,)
+def fibonacci(n: int) -> list[int]:
+ """Return first n numbers of Fibonacci sequence"""
+ if n <= 0:
+ return []
+ elif n == 1:
+ return [0]
-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
- sequence = [0, 1]
- while len(sequence) < n:
- sequence.append(sequence[-1] + sequence[-2])
- return sequence
- return (fibonacci,)
+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()
-def _():
- import matplotlib.pyplot as plt
- from PIL import Image
+ # 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
- 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
[email protected](hide_code=True)
+def plot(plot_data):
plot_dictionary(plot_data)
- return (plot_dictionary,)
+ return
+
+
[email protected](hide_code=True)
+def _(sample_data):
+ plot_dictionary(sample_data)
+ return
+
+
+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),
+ }
@app.cell(hide_code=True)
@@ -96,11 +103,7 @@ def _():
"2022": 250,
"2023": 300,
}
- return (plot_data,)
-
[email protected](hide_code=True)
-def _(plot_dictionary):
# Example usage of plot_dictionary
sample_data = {
"Apple": 30,
@@ -109,24 +112,7 @@ def _(plot_dictionary):
"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,)
+ return plot_data, sample_data
if __name__ == "__main__":
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index cbde6af156..4676b609f4 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -611,7 +611,12 @@ class Cell:
# With an exception for tests that should act as if it's in runtime.
if "PYTEST_CURRENT_TEST" not in os.environ:
if self._app._app._setup is not None:
- refs = {**self._app._app._setup._glbls, **refs}
+ from_setup = {
+ k: v
+ for k, v in self._app._app._setup._glbls.items()
+ if k in self._cell.refs
+ }
+ refs = {**from_setup, **refs}
try:
if self._is_coroutine:
diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.py
index 7277c0470e..124042961d 100644
--- a/tests/_ast/test_cell.py
+++ b/tests/_ast/test_cell.py
@@ -282,6 +282,102 @@ class TestCellRun:
assert cyclic() == 1
+class TestReusableCell:
+ @staticmethod
+ def test_run_ok_with_setup_dep(app) -> None:
+ with app.setup:
+ z = 1
+
+ @app.cell
+ def _():
+ y = 1
+ return (y,)
+
+ @app.cell
+ def uses_setup(y):
+ # non transitive
+ x = y - z
+ x # noqa: B018
+ return
+
+ output, defs = uses_setup.run()
+ assert output == 0
+ assert defs == {"x": 0}
+
+ output, defs = uses_setup.run(y=2)
+ assert output == 1
+ assert defs == {"x": 1}
+
+ output, defs = uses_setup.run(z=2)
+ assert output == -1
+ assert defs == {"x": -1}
+
+ @staticmethod
+ def test_run_ok_with_setup_dep_rev_abc(app) -> None:
+ # Arguments are alphabetized
+ with app.setup:
+ x = 1
+
+ @app.cell
+ def _():
+ y = 1
+ return (y,)
+
+ @app.cell
+ def uses_setup(y):
+ z = y - x
+ z # noqa: B018
+ return
+
+ output, defs = uses_setup.run()
+ assert output == 0
+ assert defs == {"z": 0}, dict(defs)
+
+ output, defs = uses_setup.run(y=2)
+ assert output == 1
+ assert defs == {"z": 1}
+
+ output, defs = uses_setup.run(x=2)
+ assert output == -1
+ assert defs == {"z": -1}
+
+ @staticmethod
+ def test_run_setup_declares_more(app) -> None:
+ # Arguments are alphabetized
+ with app.setup:
+ x = 1
+ # a is important because it's an additional def that gets
+ # inserted into the runtime
+ a = 1
+
+ @app.function
+ def something_normally_scoped_for_a():
+ return 1 + a
+
+ @app.cell
+ def _():
+ y = 1
+ return (y,)
+
+ @app.cell
+ def uses_setup(y):
+ z = 0 * something_normally_scoped_for_a() + y - x
+ z # noqa: B018
+ return
+
+ output, defs = uses_setup.run()
+ assert output == 0
+ assert defs == {"z": 0}, dict(defs)
+
+ output, defs = uses_setup.run(y=2)
+ assert output == 1
+ assert defs == {"z": 1}
+
+ output, defs = uses_setup.run(x=2)
+ assert output == -1
+ assert defs == {"z": -1}
+
+
def help_smoke() -> None:
app = App()