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.

example: add complete fastapi example (#2685)

Myles Scolnickae4a66e3ce21
diff --git a/docs/guides/deploying/programmatically.md b/docs/guides/deploying/programmatically.md
index bcf3243eb0..be9e47ab72 100644
--- a/docs/guides/deploying/programmatically.md
+++ b/docs/guides/deploying/programmatically.md
@@ -35,3 +35,5 @@ if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=8000)
```
+
+For a more complete example, see the [FastAPI example](https://github.com/marimo-team/marimo/tree/main/examples/frameworks/fastapi).
diff --git a/examples/frameworks/README.md b/examples/frameworks/README.md
new file mode 100644
index 0000000000..262a2223d8
--- /dev/null
+++ b/examples/frameworks/README.md
@@ -0,0 +1,11 @@
+# Frameworks 🧩
+
+These examples show how to use marimo with various web/ASGI frameworks.
+
+> [!TIP]
+> Submit a
+> [pull request](https://github.com/marimo-team/marimo/pulls) to add an example!
+
+## Running examples
+
+Each example includes a `README.md` file with instructions for running it.
diff --git a/examples/frameworks/fastapi/README.md b/examples/frameworks/fastapi/README.md
new file mode 100644
index 0000000000..00e404629f
--- /dev/null
+++ b/examples/frameworks/fastapi/README.md
@@ -0,0 +1,16 @@
+# FastAPI + marimo
+
+This is a simple example of how to use FastAPI with marimo. This example programmatically creates multiple marimo apps from a directory, and then serves them as a single FastAPI app.
+
+This example includes:
+
+- Authentication
+- Serving multiple marimo apps from a directory
+- A home page listing all the apps
+- Loading environment variables from a `.env` file
+- Basic logging
+
+## 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/main.py b/examples/frameworks/fastapi/main.py
new file mode 100644
index 0000000000..0d2da7a4e4
--- /dev/null
+++ b/examples/frameworks/fastapi/main.py
@@ -0,0 +1,146 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "fastapi",
+# "marimo",
+# "starlette",
+# "jinja2",
+# "itsdangerous",
+# "python-dotenv",
+# "python-multipart",
+# "passlib",
+# "pydantic",
+# ]
+# ///
+from typing import Callable, Coroutine
+from fastapi import FastAPI, Request, Response, Depends, HTTPException, status
+from fastapi.responses import RedirectResponse
+from fastapi.templating import Jinja2Templates
+from starlette.middleware.sessions import SessionMiddleware
+from pydantic import BaseModel
+import marimo
+import os
+import logging
+from dotenv import load_dotenv
+from fastapi import Form
+
+# Load environment variables
+load_dotenv()
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+ui_dir = os.path.join(os.path.dirname(__file__), "..", "..", "ui")
+templates_dir = os.path.join(os.path.dirname(__file__), "templates")
+
+server = marimo.create_asgi_app()
+app_names: list[str] = []
+
+for filename in os.listdir(ui_dir):
+ if filename.endswith(".py"):
+ app_name = os.path.splitext(filename)[0]
+ app_path = os.path.join(ui_dir, filename)
+ server = server.with_app(path=f"/{app_name}", root=app_path)
+ app_names.append(app_name)
+
+# Create a FastAPI app
+app = FastAPI()
+
+# Set up Jinja2 templates
+templates = Jinja2Templates(directory=templates_dir)
+# Simulated user database (replace with a real database in production)
+users = {"admin": "password123"}
+
+
+class LoginForm(BaseModel):
+ username: str
+ password: str
+
+
+def get_current_user(request: Request):
+ username = request.session.get("username")
+ if username is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated"
+ )
+ return username
+
+
+async def auth_middleware(
+ request: Request,
+ call_next: Callable[[Request], Coroutine[None, None, Response]],
+) -> Response:
+ if request.url.path == "/login":
+ return await call_next(request)
+
+ if "username" not in request.session:
+ return RedirectResponse(url="/login", status_code=status.HTTP_302_FOUND)
+
+ return await call_next(request)
+
+
+async def get_login(request: Request):
+ return templates.TemplateResponse("login.html", {"request": request})
+
+
+async def post_login(
+ request: Request,
+ username: str = Form(...),
+ password: str = Form(...)
+):
+ if username in users and password == users[username]:
+ request.session["username"] = username
+ logger.info(f"User {username} logged in successfully")
+ return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
+ logger.warning(f"Failed login attempt for user {username}")
+ return templates.TemplateResponse(
+ "login.html", {"request": request, "error": "Invalid credentials"}
+ )
+
+
+async def logout(request: Request):
+ username = request.session.get("username")
+ request.session.clear()
+ logger.info(f"User {username} logged out")
+ return RedirectResponse(url="/login")
+
+
+async def home(request: Request, username: str = Depends(get_current_user)):
+ return templates.TemplateResponse(
+ "home.html", {"request": request, "username": username, "app_names": app_names}
+ )
+
+
+async def root():
+ return {"message": "pong"}
+
+
[email protected]_handler(HTTPException)
+async def http_exception_handler(request: Request, exc: HTTPException):
+ logger.error(f"HTTP error occurred: {exc.detail}")
+ return templates.TemplateResponse(
+ "error.html",
+ {"request": request, "detail": exc.detail},
+ status_code=exc.status_code,
+ )
+
+
+app.mount("/", server.build())
+
+# Add session middleware
+app.add_middleware(
+ SessionMiddleware, secret_key=os.getenv("SECRET_KEY", "your-secret-key")
+)
+
+# Run the server
+if __name__ == "__main__":
+ import uvicorn
+
+ uvicorn.run(app, host="localhost", port=8000, log_level="info")
diff --git a/examples/frameworks/fastapi/templates/home.html b/examples/frameworks/fastapi/templates/home.html
new file mode 100644
index 0000000000..cba34ba8e1
--- /dev/null
+++ b/examples/frameworks/fastapi/templates/home.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Home</title>
+ <script src="https://cdn.tailwindcss.com"></script>
+ </head>
+ <body class="bg-gray-100">
+ <div class="container mx-auto px-4 py-8">
+ <div class="flex justify-between items-center mb-6">
+ <h1 class="text-3xl font-bold">Welcome, {{ username }}!</h1>
+ <a href="/logout" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"> Logout </a>
+ </div>
+ <h2 class="text-2xl font-semibold mb-4">Available Applications:</h2>
+ <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
+ {% for app_name in app_names %}
+ <a href="/{{ app_name }}" class="block" target="{{ app_name }}">
+ <div class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 p-4">
+ <h3 class="text-lg font-semibold text-blue-600 hover:text-blue-800">{{ app_name }}</h3>
+ <p class="text-gray-600 mt-2">Click to open application</p>
+ </div>
+ </a>
+ {% endfor %}
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/examples/frameworks/fastapi/templates/login.html b/examples/frameworks/fastapi/templates/login.html
new file mode 100644
index 0000000000..7d446042a8
--- /dev/null
+++ b/examples/frameworks/fastapi/templates/login.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Login</title>
+ <script src="https://cdn.tailwindcss.com"></script>
+ </head>
+ <body class="bg-gray-100 flex items-center justify-center h-screen">
+ <div class="bg-white p-8 rounded-lg shadow-md w-96">
+ <h1 class="text-2xl font-bold mb-6 text-center">Login</h1>
+ {% if error %}
+ <p class="text-red-500 mb-4">{{ error }}</p>
+ {% endif %}
+ <form action="/login" method="post" class="space-y-4">
+ <div>
+ <label for="username" class="block mb-1">Username</label>
+ <input type="text" id="username" name="username" required class="w-full px-3 py-2 border rounded-md" />
+ </div>
+ <div>
+ <label for="password" class="block mb-1">Password</label>
+ <input type="password" id="password" name="password" required class="w-full px-3 py-2 border rounded-md" />
+ </div>
+ <button type="submit" class="w-full bg-blue-500 text-white py-2 rounded-md hover:bg-blue-600">Login</button>
+ </form>
+ </div>
+ </body>
+</html>