Running the marimo backend programmatically

marimo can be run programmatically using the marimo module. This is useful when you want to run marimo as part of a larger application or when you need to customize the behavior of marimo (e.g. middleware, custom error handling, authentication, routing, etc).

FastAPI Example

Here’s an example of how you can run a marimo application programmatically using FastAPI:

from typing import Annotated, Callable, Coroutine
from fastapi.responses import HTMLResponse, RedirectResponse
import marimo
from fastapi import FastAPI, Form, Request, Response

# Create a marimo asgi app
server = (
    .with_app(path="", root="./pages/")
    .with_app(path="/dashboard", root="./pages/")
    .with_app(path="/sales", root="./pages/")

# Create a FastAPI app
app = FastAPI()

app.add_route("/login", my_login_route, methods=["POST"])


# Run the server
if __name__ == "__main__":
    import uvicorn, host="localhost", port=8000)