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.

Documentation: pydantic model for query params (#4960)

Alexander Kislukhinf48589746b7a
diff --git a/docs/api/query_params.md b/docs/api/query_params.md
index d9e80a5e81..c7c66ae5b2 100644
--- a/docs/api/query_params.md
+++ b/docs/api/query_params.md
@@ -1,5 +1,7 @@
# Query Parameters
+Query parameters are key-value pairs appended to the end of a URL to pass data to the server or customize a request.
+
Use `mo.query_params` to access query parameters passed to the notebook. You
can also use `mo.query_params` to set query parameters in order to keep track
of state in the URL. This is useful for bookmarking or sharing a particular
@@ -7,6 +9,42 @@ state of the notebook while running as an application with `marimo run`.
::: marimo.query_params
+## Pydantic Models for Query Parameters
+
+One of the use cases for URL query parameters is to set the initial state of UI elements.
+
+Passing query parameters into a Pydantic model helps document and validate the parameters.
+
+
+```python
+import marimo as mo
+from pydantic import BaseModel, Field
+
+class MyModel(BaseModel):
+ r: int = Field(28, ge=0, le=255, description="Red Channel")
+ g: int = Field(115, ge=0, le=255, description="Green Channel")
+ b: int = Field(97, ge=0, le=255, description="Blue Channel")
+ message: str = Field("<br>", description="Some text")
+
+model = MyModel(**mo.query_params().to_dict())
+
+# UI with initial state from query params
+r_slider = mo.ui.slider(start=0, stop=255, step=1, label="R", value=model.r)
+g_slider = mo.ui.slider(start=0, stop=255, step=1, label="G", value=model.g)
+b_slider = mo.ui.slider(start=0, stop=255, step=1, label="B", value=model.b)
+```
+
+In the next cell: (see [live](https://marimo.app/l/03egkc?g=255))
+```python
+bg_color = f"rgb({r_slider.value},{g_slider.value},{b_slider.value})"
+mo.vstack([
+ r_slider, g_slider, b_slider,
+ mo.Html(model.message + bg_color).style(background_color=bg_color, text_align="center")
+])
+```
+
+When using [marimo apps mounted to FastAPI](../guides/deploying/programmatically.md), the Pydantic model can be passed into the API documentation for the main app.
+
!!! note "CLI arguments"
You can also access command-line arguments passed to the notebook using
diff --git a/docs/guides/deploying/programmatically.md b/docs/guides/deploying/programmatically.md
index 4764ad0b2d..d84ddc6956 100644
--- a/docs/guides/deploying/programmatically.md
+++ b/docs/guides/deploying/programmatically.md
@@ -121,3 +121,52 @@ The `request` object provides access to:
- `request.user`: User data added by authentication middleware
- `request.url`: URL information including path, query parameters
- `request.meta`: Metadata added by your custom middleware
+
+
+### Documenting and Validating Query Parameters
+
+When mounted apps accept [query parameters](../../api/query_params.md), it can be helpful to declare, validate, and document them with the help of a [Pydantic model](https://fastapi.tiangolo.com/tutorial/query-param-models/).
+
+If a marimo app called `notebooks/items.py` is mounted to `/items`, declaring an endpoint with the same route will take the query parameters through Pydantic model validation first, then redirect to the marimo endpoint.
+
+
+```python
+# src/main.py
+from fastapi import FastAPI, Request, Query
+from fastapi.responses import RedirectResponse
+from marimo import create_asgi_app
+from pathlib import Path
+from pydantic import BaseModel, Field
+from typing import Annotated, Literal
+from urllib.parse import urlencode
+
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+async def marimo_items(
+ request: Request, filter_query: Annotated[FilterParams, Query()]
+):
+ query_params = urlencode(filter_query.model_dump(), doseq=True)
+ return RedirectResponse(url=f"/items/?{query_params}")
+
+
+server = create_asgi_app(include_code=True, quiet=False)
+notebooks_dir = Path(__file__).parent.parent / "notebooks"
+
+for filename in notebooks_dir.iterdir():
+ if filename.suffix == ".py":
+ app_name = filename.stem
+ server = server.with_app(path=f"/{app_name}", root=filename)
+
+
+app.mount("/", server.build())
+```
\ No newline at end of file