Skip to content

Python

Mateu has a Python server-side implementation. You annotate plain Python classes, and the existing renderers (web and native) render them with zero client changes — exactly as they render the Java backend.

🎬 One wire, three languages — on YouTube
🎬 Mateu deep dives: Mateu for Python developers — on YouTube

Coming from Java? The Language Rosetta maps every declaration idiom side by side, and the parity matrix shows exactly what this server supports today.

Every Mateu renderer speaks one protocol: POST /{baseUrl}/mateu/v3/sync/{route} in, a UIIncrement JSON tree out. So the Python side does not re-implement the whole framework — it emits the same JSON. FastAPI hosts the sync endpoint; a reflection mapper turns your annotated classes into the Mateu component tree; Pydantic v2 discriminated unions produce the type discriminators the renderers expect.

The implementation lives at backend/python (DESIGN.md for the plan, README.md for status). It mirrors the C# reference behaviour, emitting the same wire JSON for the same view.

Python attributes can’t carry C#-style attributes, so:

  • Field modifiers ride inside Annotated[T, Marker(...)].
  • Class and method features are decorators.
Terminal window
pip install "mateu-ui[server]" # the package + uvicorn (any ASGI server works)

([all] is an alias of [server] today.)

The distribution is mateu-ui (the PyPI name mateu belongs to an unrelated project); it installs one top-level package, mateu_ui, and you import mateu_ui.uidl (the authoring API), mateu_ui.dtos (the wire model), mateu_ui.core (the engine) and mateu_ui.fastapi (the adapter). Versions move in lockstep with the Java artifacts: the v3.0.0 release publishes 3.0.0. Python 3.11–3.13 are tested in CI (3.14 has been seen to work too).

An app shell with a menu and a CRUD, from an empty folder (the IDE wizards — IntelliJ File › New › Project… › Mateu, VS Code Mateu: New Project…, runtime Python — generate the same kind of project):

Terminal window
mkdir my-app && cd my-app
python3 -m venv .venv && . .venv/bin/activate
pip install "mateu-ui[server]"

views.py — the entity, where its rows live, the CRUD over it and the app shell whose menu leads to it:

from enum import Enum
from typing import Annotated
from mateu_ui.uidl import ui, title, app, menu_item, Crud, EditableOnlyWhenCreating, Required, Money
class ProductStatus(Enum):
AVAILABLE = "AVAILABLE"
OUT_OF_STOCK = "OUT_OF_STOCK"
class Product:
# a product code the user types on create — without EditableOnlyWhenCreating() the id is
# technical: the new form has no input for it and save() must assign it (see "CRUD" below)
id: Annotated[str, Required(), EditableOnlyWhenCreating()] = ""
name: Annotated[str, Required()] = ""
price: Annotated[float, Money()] = 0.0
status: ProductStatus = ProductStatus.AVAILABLE
store: dict[str, Product] = {} # shared: the view models are created fresh on every request
@ui("products")
@title("Products")
class Products(Crud[Product]):
def fetch(self, search):
return [p for p in store.values() if not search or search.lower() in p.name.lower()]
def get(self, id): return store.get(id)
def save(self, entity): store[entity.id] = entity
def delete(self, id): store.pop(id, None)
@app("My app")
class Shell:
@menu_item("Products")
def products(self) -> Products: return Products()

main.py:

from fastapi import FastAPI
from mateu_ui.fastapi import add_mateu
import views
app = FastAPI()
add_mateu(app, views)

The server answers the Mateu API; to open it in a browser it also needs the web renderer, a jar on Maven Central (mateu-ui does not package it). Download the one of your version and point MATEU_UI at it:

Terminal window
V=3.0.5
curl -LO https://repo1.maven.org/maven2/io/mateu/mateu-vaadin/$V/mateu-vaadin-$V.jar
MATEU_UI=mateu-vaadin-$V.jar uvicorn main:app --port 8594 # http://localhost:8594

New creates, a row opens the record, Edit edits; Required() is checked in the browser and on the server. Add a screen by writing its @ui class (see Forms) and a @menu_item method returning it. To deploy, run it like any ASGI app — uvicorn main:app --host 0.0.0.0 --port 8080 (uvicorn listens on 127.0.0.1 unless told otherwise) — with MATEU_UI pointing at the jar or at its extracted static/ folder.

Terminal window
cd backend/python
python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[dev,all]"
uvicorn samples.demo.main:app --host 0.0.0.0 --port 8594 # serves the sync API
pytest # golden tests

Open it in a browser: the server serves the web renderer’s page too when you tell it where the renderer is — add_mateu(app, views, ui="<path>") or the MATEU_UI environment variable, pointing at the io.mateu:mateu-vaadin (or mateu-redwood) jar of the version you target, or at its extracted static/ folder. The jar is on Maven Central; mateu-ui does not package it:

Terminal window
V=3.0.5
curl -LO https://repo1.maven.org/maven2/io/mateu/mateu-vaadin/$V/mateu-vaadin-$V.jar
MATEU_UI=mateu-vaadin-$V.jar uvicorn samples.demo.main:app --port 8594 # http://localhost:8594

The page answers the mount and every deep link under it, the renderer’s assets are served at the origin root, your own routes keep winning, and nothing under /mateu is ever answered with the page — the same rules as a Java app. Without ui/MATEU_UI the server answers the sync API only (a browser opening the mount gets a short hint page, status 404, that says so), for a renderer served elsewhere: the React Native app (cd frontend/app/react-native && EXPO_PUBLIC_MATEU_BACKEND_PORT=8594 npx expo start --web — or EXPO_PUBLIC_MATEU_BACKEND_URL=http://localhost:8594; the server must list that origin in its CORS settings), the IntelliJ plugin, or the Vaadin renderer’s dev server (MATEU_BACKEND=http://localhost:8594 npm run dev in frontend/web/monorepo/apps/vaadin: its proxy forwards /mateu to the backend). Started with --host 0.0.0.0 (uvicorn’s default is 127.0.0.1), the server is reachable from the iOS simulator and the Android emulator too.

Wire it up:

from fastapi import FastAPI
from mateu_ui.fastapi import add_mateu
from samples.demo import views # a module holding your @ui / @app classes
app = FastAPI()
add_mateu(app, views)
add_mateu(
app, views,
cors_origins=["https://app.example.com"], # CORS is OFF unless you list origins
secrets_provider=lambda key: vault.read(key), # ${secret.KEY} in proxied REST sources
dev=False, # exception detail in error toasts (or MATEU_DEV)
proxy_timeout_seconds=30,
)
  • Identity. EyesOnly / ReadOnlyUnless / DisabledUnless / @eyes_only match the caller’s Identity(roles, groups, scopes, permissions). Mateu does not authenticate: by default it takes the identity your app established — request.state.mateu_identity (set by your dependency or middleware), else Starlette’s AuthenticationMiddleware. Verify tokens in your app and hand Mateu the result:

    from mateu_ui.fastapi import identity_from_claims # also in mateu_ui.core
    @app.middleware("http")
    async def authenticate(request, call_next):
    claims = verify_with_your_idp(request.headers.get("authorization")) # e.g. PyJWT + JWKS
    if claims is not None:
    request.state.mateu_identity = identity_from_claims(claims)
    return await call_next(request)

    No identity → every gate denies. identity_provider= replaces the default with your own parameterless provider.

  • Secrets. secrets_provider(key) resolves ${secret.KEY}; unset → the env var MATEU_SECRET_<KEY> (only that prefix, never an arbitrary variable). Only proxied fetches (__restfetch__) see them.

  • CORS (breaking change). add_mateu used to allow every origin. Now CORS is off unless cors_origins lists them; cors=True without origins raises. A renderer served by the same app needs none.

  • Errors. An unhandled exception answers an error toast, never a raw 500 — the same texts as Java and .NET (“Something went wrong” / “An unexpected error occurred. Reference: <id>”), the reference being the request’s correlation id (also in the X-Mateu-Correlation-Id header and the logged traceback). dev=True / MATEU_ERRORS_DETAILED=true shows the exception; raise mateu_ui.uidl.UserFacingException("…", title="…") for a message written for the user. A denied action answers 403.

  • Concurrency. The handler runs in the threadpool (a slow proxied upstream never blocks the event loop); per-request state lives in ContextVars.

  • Audience is a projection, not security. Audience() / @audience read the client-controlled appState["audience"] — any caller can send any value. Tailor screens with it; hide data with EyesOnly. Like Java and .NET, an @audience action is therefore never refused at invocation; an Audience() row field is left out of listing columns AND row data, like an EyesOnly one.

  • Nested forms and held objects. A public annotated attribute holding a data object is a nested form: it is drawn, its values travel in the state and the client edits them (bound into the view’s own copy, never into a shared class-level default). An object the view only holds — a service, an HTTP client, its configuration — is spelled _name, ClassVar[...] or Final[...]: never sent, never written. EyesOnly holds inside nested objects, grid rows and a wizard’s state too.

  • Bounded by default. A listing page asks for at most 500 rows (listing_max_page_size / MATEU_LISTING_MAX_PAGE_SIZE); an upload ticket sends 10 files for a single-file field and uploads_max_files_per_ticket / MATEU_UPLOADS_MAX_FILES_PER_TICKET (100) for a multiple one (then 429); each caller holds at most MATEU_IDEMPOTENCY_MAX_ENTRIES_PER_CALLER (100) keyed requests in each idempotency table, and a repeat joining a keyed run still in flight waits at most MATEU_IDEMPOTENCY_JOIN_SECONDS (60) — the handler runs in a worker thread — before the “Too many pending requests” refusal.

Every keyword argument of add_mateu(app, *sources, …). Most fall back to an environment variable, so a deployment can switch them without code.

OptionDefaultWhat it does
translatorMateu’sThe Translator for ${i18n.…} texts and the chrome.
base_url""Path prefix the endpoints are served under.
cors_originsnone (CORS off)Origins allowed to call the API. cors=True without origins raises.
identity_providerthe identity your app set (request.state.mateu_identity, else Starlette auth)Parameterless provider of the caller’s Identity.
secrets_providerenv MATEU_SECRET_<KEY>key → value for ${secret.KEY} in proxied sources.
devenv MATEU_DEVException details in error toasts.
proxy_timeout_seconds30.0Timeout of a proxied REST call.
environmentenv MATEU_ENVIRONMENTThe type: Environment overlay applied to the source catalogue (environments).
live_reloadenv MATEU_DEVDevelopment mode: specs watched, GET /mateu/dev/events + POST /mateu/dev/reload.
mcpenv MATEU_MCP_ENABLED, else offThe native MCP endpoint POST /mateu/mcp.
uienv MATEU_UIA web renderer’s static/ folder or jar, to serve the page too.
mcp_pushenv MATEU_MCP_PUSH_ENABLED, else offLive UI push (needs mcp).
mcp_push_rate_per_minuteenv MATEU_MCP_PUSH_RATE_PER_MINUTE, else 30Messages per session per rolling minute.
mcp_push_max_sessionsenv MATEU_MCP_PUSH_MAX_SESSIONS, else 1000Live UI sessions held at once.
mcp_push_max_sessions_per_ownerenv MATEU_MCP_PUSH_MAX_SESSIONS_PER_OWNER, else 20Sessions per signed-in user.
mcp_push_max_anonymous_sessions_per_addressenv MATEU_MCP_PUSH_MAX_ANONYMOUS_SESSIONS_PER_ADDRESS, else 200Anonymous sessions per client address (behind a proxy, run uvicorn with --proxy-headers).
build_idenv MATEU_BUILD_ID, else a fingerprint of the releaseThe X-Mateu-Build id (versions across teams).
oracle_cdn_urlenv MATEU_ORACLE_CDN_URLA mirror of Oracle’s CDN for the Redwood page (Oracle CDN mirror).
remotesnoneRemoteDescriptors for server-resolved micro frontends and content slots (on top of RemoteCatalogSupplier subclasses).
default_timeout_msenv MATEU_MICROFRONTENDS_DEFAULT_TIMEOUT_MS, else 500Budget of a server-resolved fragment that names none.
max_budget_msenv MATEU_MICROFRONTENDS_MAX_BUDGET_MS, else 2000The most a view waits for its fragments.
content_remote_idenv MATEU_CONTENT_SLOTS_REMOTE, else contentThe remote content slots are resolved against.
content_routeenv MATEU_CONTENT_SLOTS_ROUTE, else /content-slots/{key}A slot’s route on the content remote.
self_base_urlenv MATEU_SELF_BASE_URLThis server’s origin, for a remote registered as a path on it.
content_slots_descriptor_enabledenv MATEU_CONTENT_SLOTS_DESCRIPTOR_ENABLED, else offServe the __content_slots__ descriptor action.
remote_registry, identity_strategies, fragment_cache_store, correlation_id_provider, resolution_listenersMateu’sReplace (or add to) the micro-frontend collaborators.

A @ui class becomes a routed form. Public type-hinted fields become fields (the type is inferred: str→string, int→integer, float/Decimal→number, bool→bool, date→date, datetime→dateTime, time→time, Enum→dropdown). Required() makes a field required and is enforced server-side. A @button method returning a Message shows a toast.

from enum import Enum
from typing import Annotated
from mateu_ui.uidl import ui, title, subtitle, button, Required, Section, Message
class Role(Enum):
GUEST = "GUEST"
ADMIN = "ADMIN"
@ui("person")
@title("Person")
@subtitle("Personal data")
class Person:
name: Annotated[str | None, Required(), Section("Identity")] = None
age: int = 0
subscribed: Annotated[bool, Section("Preferences")] = False
role: Role = Role.GUEST # Enum → dropdown
@button()
def save(self) -> Message:
return Message(f"Saved {self.name}")

Section("…") on the first field of a group starts a titled card that following fields join.

A form lays out in one column with up to 6 visible fields and two from 7 on (counted over the whole form, like the Java and .NET servers — see how many columns). @form_layout(columns=N) on the class fixes it (columns=2 keeps two columns on a small form); a @zones form keeps two.

Derive from Crud[T] and override fetch (and, as needed, get / save / delete). You get a searchable listing — a table on desktop, cards on mobile — plus full detail / edit / new flows (routes /x, /x/{id}, /x/{id}/edit, /x/new), with Required() validation on save.

@ui("reservations")
@title("Reservations")
class Reservations(Crud[Reservation]):
def fetch(self, search):
return [r for r in store if not search or search in r.locator]
def get(self, id): return store_by_id.get(id)
def save(self, entity):
if not entity.id: # a NEW record: the store assigns its id
entity.id = f"R-{len(store_by_id) + 1:04}"
store_by_id[entity.id] = entity
def delete(self, id): store_by_id.pop(id, None)

Who chooses the id. A plain id is a technical id: the creation form has no input for it and a create never takes one from the client — the store assigns it in save, as above. A create the store saves with the id still blank is refused with “The record was saved without an id…” instead of answering “Saved” (every new record would otherwise land on the same empty key). When the user should type the id (a product code, a locator), mark it Annotated[str, Required(), EditableOnlyWhenCreating()]: it is an input on the new form and read-only afterwards, and a create whose id already exists is refused (“A record with this id already exists…”). GeneratedValue() marks an id the server fills into the creation form.

fetch is the only method you must write, but a crud that writes must also override save and delete: their defaults refuse with a “Not implemented” error naming the override, so a crud that forgot them can never answer “Saved” and drop the change. A crud that should not create or delete turns those buttons off in display() (CrudDisplay) instead.

The listing renders a smart search bar whose filters come straight from the entity: enums become multi-selects (IN over the picked values), date/datetime fields become from–to date ranges, numerics annotated RangeFilter() become min–max ranges, and strings/bools/plain numbers keep single-value widgets. The values are applied automatically over what fetch returns — no filter code to write:

class Reservation:
id: str = ""
guest: str = ""
channel: Channel = Channel.WEB # multi-select filter
arrival: date = date(2026, 1, 1) # date-range filter
total: Annotated[float, RangeFilter()] = 0.0 # number-range filter

Decorate the crud class with @edit_in_drawer and New/row clicks open the create/edit form in a drawer sliding over the listing (the listing never unmounts; saving persists, closes the drawer and refreshes the rows in place).

A record’s page (/x/{id}) is its read-only form. For other content, the entity subclasses DetailContentSupplier and returns the component to show from detail_content() — for instance an ItemOverview built from the record. The page title and toolbar (Back to list, Edit) stay the crud’s, the edit and create forms keep their forms, and returning None keeps the default form for that record:

from mateu_ui.uidl.components import Text
class StudentOverview(ItemOverview):
key_info: Text
history: Annotated[Text, Panel("History")]
def __init__(self, student: "Student") -> None:
self.key_info = Text(text=f"Email: {student.email}")
self.history = Text(text="Enrolled since 2024")
class Student(DetailContentSupplier):
id: str = ""
email: str = ""
def detail_content(self):
return StudentOverview(self)

Two more archetypes mirror the Java orchestrators: subclass CollectionDetail (searchable card list on the left, the selected item’s detail re-rendered in place on the right) or GeneralOverview (a record context switcher over the selected record’s overview). Both are built on the fluent FormField primitive — a live field you can compose into any fluent tree.

Customise each screen: creation form, detail, editor

Section titled “Customise each screen: creation form, detail, editor”

A crud is four screens — the listing (/customers), the creation form (/customers/new), the record’s read-only detail (/customers/C-001) and the editor (/customers/C-001/edit) — and by default they all show the entity’s fields. Java has three levels to make them differ; this port has two of them:

You want…LevelHow in Python
A field not shown on one screen1HiddenInCreate(), HiddenInView(), HiddenInEditor(), HiddenInList() in the Annotated[...]
A code the user types once, then never changes1EditableOnlyWhenCreating()
A field shown but never typed (set by the store)1ReadOnly() (+ HiddenInCreate() when New should not show it)
A field only some users may change, or see1ReadOnlyUnless(roles=[…]), EyesOnly(roles=[…])
No New, no Edit1override can_create() / can_edit(), or display()
New starts filled in2the entity’s class defaults — see below
A value computed when a record is opened2override get(id) — it serves the detail and the editor
Different classes per screen3Listing[Row] + Navigable / Editable / Creatable / Deletable

Level 1 — same fields, different per screen:

from datetime import date
from typing import Annotated
from mateu_ui.uidl import (Crud, EditableOnlyWhenCreating, HiddenInCreate, HiddenInEditor,
HiddenInList, HiddenInView, ReadOnly, ReadOnlyUnless, Required, title, ui)
class Customer:
id: Annotated[str, Required(), EditableOnlyWhenCreating()] = "" # typed on New, read-only afterwards
name: Annotated[str, Required()] = ""
email: str = ""
customer_since: Annotated[str, HiddenInCreate(), ReadOnly()] = "" # set by the store, never typed
internal_notes: Annotated[str, HiddenInList(), HiddenInView()] = "" # only on the two forms
credit_limit: Annotated[float, ReadOnlyUnless(roles=["manager"])] = 1000.0 # only a manager changes it
open_orders: Annotated[int, HiddenInCreate(), HiddenInEditor(), HiddenInList()] = 0 # only on the detail
STORE: dict[str, Customer] = {}
def open_orders_of(customer_id: str) -> int:
return 0 # e.g. a query to the orders service
@ui("customers")
@title("Customers")
class Customers(Crud[Customer]):
def fetch(self, search):
return list(STORE.values())
def get(self, id):
return STORE.get(id)
def save(self, entity):
if not entity.customer_since: # New does not show it
entity.customer_since = date.today().isoformat()
STORE[entity.id] = entity
def delete(self, id):
STORE.pop(id, None)

New shows id, name, email, internalNotes and creditLimit (read-only but for a manager); the detail id, name, email, customerSince, creditLimit and openOrders; the editor the same as New plus customerSince, with id and customerSince read-only. What a form does not let the user write is never taken from the browser on save.

Level 2 — same class, other content. The crud builds New from Customer(), and the detail and the editor from get(id). So the creation form’s defaults are the class defaults (credit_limit = 1000.0 above), and a value computed when a record is opened goes in get:

@ui("customers")
@title("Customers")
class Customers(Crud[Customer]):
# …fetch, save and delete as above
def get(self, id):
customer = STORE.get(id)
if customer is not None:
customer.open_orders = open_orders_of(id) # computed when the record is opened
return customer

Level 3 — a class per screen. Declare the capabilities one by one and give each screen its own class. Here a detail and a creation form of their own — the next code already filled in — and no editor at all (no Edit button, no /edit route):

from mateu_ui.uidl import Creatable, Listing, ListingData, Navigable, SearchRequest
class CustomerCard:
name: str = ""
email: str = ""
activity: str = ""
class NewCustomer:
id: Annotated[str, Required(), EditableOnlyWhenCreating()] = ""
name: Annotated[str, Required()] = ""
@ui("directory")
@title("Customers")
class CustomerDirectory(Listing[Customer], Navigable[CustomerCard, str], Creatable[NewCustomer, str]):
def search(self, request: SearchRequest, http=None):
return ListingData.of(list(STORE.values()))
def view(self, id, http=None):
c = STORE[id]
card = CustomerCard()
card.name, card.email, card.activity = c.name, c.email, f"customer since {c.customer_since}"
return card
def creation_form(self, http=None):
form = NewCustomer()
form.id = f"C-{len(STORE) + 1:03}" # the next free code
return form
def create(self, form, http=None):
customer = Customer()
customer.id, customer.name = form.id, form.name
customer.customer_since = date.today().isoformat()
STORE[customer.id] = customer
return customer.id

Add Editable[Editor, str] (edit(id) + save(editor)) for an editor class of its own and Deletable[str] for Delete. The Java guide walks the same example through the three levels: Customise each screen.

When you don’t want the whole CRUD pack, subclass Listing — one method — and grow the page by declaring capabilities as extra base classes (multiple inheritance is the Python idiom for the Java capability interfaces):

@ui("/orders")
class Orders(Listing[OrderRow], Searchable, Filterable[OrderFilters]):
def search(self, request: SearchRequest, http=None):
text = request.search_text # filled because Searchable
filters = self.filters(request) # typed OrderFilters, from Filterable
return ListingData.of(repo.find(text, filters, request.pageable))

A bare Listing[Row] is just the table (sorting + pagination free). Then:

DeclareContractYou get
Searchable— (marker)the search box
Filterable[F]— (marker; or a filters_class attribute)the filter bar, built reflectively from F
Navigable[Detail, Id]view(id)clickable rows + the /:id detail page
Editable[Editor, Id]edit(id) + save(editor)editing — in a drawer over the listing when not navigable
Creatable[Form, Id]creation_form() + create(form)the New button + /new form
Deletable[Id]delete_all_by_id(ids)row selection + the Delete button

Capability methods receive typed objects (the framework hydrates the submitted state — save(editor), create(form)). ListingData.of(rows) sorts and pages in memory; pass an explicit total_elements to push paging to the database. Crud[T] is the full pack — all capabilities at once. To drop a built-in affordance, override display() and return a CrudDisplay with that toggle off — e.g. no New button:

import dataclasses
from mateu_ui.uidl import Crud, CrudDisplay, Toggle
class Reservations(Crud[Reservation]):
def display(self):
return dataclasses.replace(CrudDisplay.defaults(), create=Toggle.off)

Toggle.off does not send the affordance at all and the server refuses it if forced; Toggle.disabled shows it inert. CrudDisplay covers create, delete, save_and_next and error_banner. Note: Searchable keeps its second role as the selector-field marker, mirroring Java’s interface/annotation pair.

An @app class is the application shell; each @menu_item method contributes a menu entry that navigates to the view it returns (read from the method’s return annotation).

@app("My Python Mateu app")
class DemoApp:
@menu_item("Reservations")
def reservations(self) -> Reservations: return Reservations()
@menu_item("Person")
def person(self) -> Person: return Person()

Derive from Wizard, tag each field with Step(n), and implement complete(). Mateu renders a progress bar plus Back/Next; the step + field values round-trip through component state. Decorate the class with @wizard_progress("steps") for connected step bullets, or @wizard_progress("rail") for the guided-process lateral rail (a sticky right band with a big current | total counter over the vertical step list).

@ui("signup")
@title("Sign up")
class SignupWizard(Wizard):
email: Annotated[str | None, Step(1)] = None
password: Annotated[str | None, Step(2), Password()] = None
def complete(self) -> Message:
return Message(f"Welcome {self.email}")

Tag consecutive fields with Tab("Name") to group them into a tab strip. Field stereotypes:

MarkerEffect
Multiline()multi-line text area
Password()password input
Money()tagged money so the renderer formats it as currency
PlainText()read-only plain text (also valid class-level via @plain_text)
Stereotype("…")an explicit stereotype
class Profile:
name: Annotated[str | None, Tab("Identity")] = None
secret: Annotated[str | None, Tab("Identity"), Password()] = None
bio: Annotated[str | None, Tab("About"), Multiline()] = None
salary: Annotated[float, Tab("About"), Money()] = 0.0
from mateu_ui.uidl import kpi, fab, shortcut, button, compact, confirm_on_navigation_if_dirty
@ui("dashboard")
@compact # high-density rendering
@confirm_on_navigation_if_dirty # warn before leaving with unsaved changes
class Dashboard:
@kpi("Open tickets")
def open_tickets(self) -> str: return "42"
@fab("plus", "Add", 0) # floating action button
def add(self) -> Message: return Message("Added")
@button()
@shortcut("ctrl+s") # keyboard shortcut
def save(self) -> Message: return Message("Saved")

Dashboards, foldouts & UX-pattern components

Section titled “Dashboards, foldouts & UX-pattern components”

The UX-pattern components from the Java backend are available as fluent components in mateu_ui.uidl.components — they emit the exact same wire JSON, so every renderer that supports them renders the Python backend unchanged:

ComponentPurpose
MetricCard (+ MetricTrend)KPI tile: title, value, unit, trend (up/down/neutral), drill-in action_id
Scoreboardhorizontal band of metric cards
DashboardPaneltitled tile wrapping any component; col_span/row_span
ResponsiveGrid (+ GridTrack)responsive grid: column tracks (GridTrack.fill()/hug()/fixed(...)), per-child col_spans, stack_below breakpoint (DashboardLayout is the simpler grid, for a uniform column count)
FoldoutPanel / FoldoutLayoutFoldout: a fixed overview with lateral fold-out panels
HeroSectionbig page hero: title, subtitle, background image, slotted content
EmptyStatefriendly “nothing here yet” placeholder with an optional call-to-action
Skeleton (+ SkeletonVariant)shimmering loading placeholder (text/card/grid/form)
Gantt / GanttTaskread-only Gantt/timeline chart (ISO dates, progress 0–100, color)

The declarative archetypes compose them from your fields, exactly like the Java Dashboard/Foldout/ItemOverview/Welcome orchestrators. Declare type-hinted fields holding components; mark titled panels with Panel(...) inside Annotated[...] (the analogue of Java’s @Panel):

from datetime import date
from typing import Annotated
from mateu_ui.uidl import ui, title, Dashboard, Panel
from mateu_ui.uidl.components import MetricCard, MetricTrend, Gantt, GanttTask
@ui("dashboard")
@title("Sales dashboard")
class SalesDashboard(Dashboard):
# consecutive MetricCards group into a full-width Scoreboard KPI band
revenue: MetricCard = MetricCard(title="Revenue", value="1.2", unit="M€",
trend=MetricTrend.up, action_id="openRevenue")
incidents: MetricCard = MetricCard(title="Incidents", value="3", trend=MetricTrend.down)
# Panel(...) fields become titled tiles on a responsive grid
plan: Annotated[Gantt, Panel("Rollout plan", col_span=2)] = Gantt(tasks=(
GanttTask(id="t1", title="Design", start=date(2026, 7, 1), end=date(2026, 7, 20),
progress=80.0),
))
def open_revenue(self): # runs when the Revenue tile is clicked
...
  • Dashboard — consecutive MetricCard fields → Scoreboard band; Panel(...) fields → titled tiles on a ResponsiveGrid; other component fields land on the grid as-is. Override columns() to fix the column count.
  • Foldout — the first component field without Panel is the always-visible overview; Panel(title, subtitle, icon, open) fields are lateral fold-out panels.
  • ItemOverview — the first component field without Panel is the key-info panel (left, sticky); Panel(title) fields become tabs on the right. Override panel_width().
  • Welcome — fluent Button fields become hero call-to-action buttons; Panel(title) fields become highlight tiles below. Override hero_title() / hero_subtitle() / hero_image().

For full control, subclass ComponentTreeSupplier and return any fluent component tree:

from datetime import date
from mateu_ui.uidl import ui, title, ComponentTreeSupplier
from mateu_ui.uidl.components import Gantt, GanttTask
@ui("project-plan")
@title("Project plan")
class ProjectPlan(ComponentTreeSupplier):
def component(self) -> Gantt:
return Gantt(tasks=(
GanttTask(id="a", title="Analysis", start=date(2026, 1, 7), end=date(2026, 2, 1),
progress=100.0),
GanttTask(id="b", title="Build", start=date(2026, 2, 1), end=date(2026, 5, 1)),
))

Action ids referenced by MetricCard, EmptyState or Button components are advertised automatically and dispatch to the method of the same (camelCased) name.

  • @subtitle("…") — a subtitle under the page title.
  • @banner(BannerTheme.INFO, "Title") on a method — a banner below the header; if the method returns a string, that’s the description. Themes: INFO, SUCCESS, WARNING, DANGER.
  • HeaderBadge(color="success") in a field’s Annotated[...] — a status chip in the header strip.
  • i18n — subclass Translator, override translate, and pass it to add_mateu(..., translator=…).
  • Events — @emits("event-name") advertises an event; @subscribe_to("event", "action") runs action when that event fires.
  • Security — EyesOnly(...) on a field hides it, ReadOnlyUnless(...) / DisabledUnless(...) lock it; @eyes_only(...) on a class refuses the whole view (403, by route, type or sub-route) and hides menu entries leading to it, on a method hides the button / menu entry and refuses the call. All match the identity add_mateu resolves (see above).
class UpperTranslator(Translator):
def translate(self, key: str) -> str: return key.upper()
Section titled “Navigation links, radio groups & adaptive layout”

Annotated[str, LinkTo("/customers/${state.customerId}")] puts a navigation icon on a field (templates interpolate client-side); give the view a link(member_name) method for runtime decisions. UseRadioButtons() forces an enum to render as a radio group, and @auto_layout enables the adaptive layout inference (small enums become radios, long forms fold, section-heavy forms become tabs) — the same heuristics as the Java server.

An @app_context method of the app class becomes a selector on the app header that fixes a value for EVERY screen (the active hotel, the company…) — return the options as Option objects or (value, label) pairs, or annotate the return type as an Enum. The picked value travels in the app_state of every request:

@app("Backoffice")
class BackofficeApp:
@app_context("Hotel")
def hotel(self):
return [(h.id, h.name) for h in hotels]

Annotated[str, Signature()] renders a drawing pad (the accepted strokes land in the value as a PNG data URI) and Annotated[str, PhotoCapture()] a camera capture (JPEG data URI) — no upload endpoint, the image travels in the string. Annotated[str, TreeSelect(leaves_only=True)] unfolds the field’s dropdown as a TREE; the hierarchy comes from the view’s options(field_name) method returning options with children:

from typing import Annotated
from mateu_ui.dtos import Option # the option record lives in mateu_ui.dtos, not mateu_ui.uidl
from mateu_ui.uidl import ui, Signature, PhotoCapture, TreeSelect
@ui("checkin")
class CheckIn:
guest_signature: Annotated[str, Signature()] = ""
document_photo: Annotated[str, PhotoCapture()] = ""
zone: Annotated[str, TreeSelect()] = ""
def options(self, field_name):
if field_name == "zone":
return [
Option(value="es", label="Spain", children=[Option(value="mca", label="Mallorca")]),
Option(value="pt", label="Portugal"),
]
return []

By default fetch() returns rows and the framework filters/sorts/paginates in memory. For real databases override find — run search+filter+sort+paginate as one query (count + page inside) and the in-memory pipeline is skipped entirely:

class Orders(Crud[Order]):
def find(self, search_text, filters, pageable, criteria=()):
# filters = the plain equality values; criteria = the range and multi-select
# conditions, typed (FilterCriterion: between/gte/lte/in). pageable = Pageable(page, size, sort).
query = build_query(search_text, filters, criteria)
total = query.count()
rows = query.order_by(*pageable.sort).offset(pageable.page * pageable.size).limit(pageable.size)
return PageResult(content=list(rows), total_elements=total)

(The Python analogue of Java’s CrudStore.find.)

Several Mateu backends compose into one shell at runtime — the frontend does the fetching, no server-side proxying:

@app("Back office")
@remote_menu("Payments", "https://payments.example.com") # nests the remote menu
@remote_menu("Billing", "https://billing.example.com", explode=True) # inlines its entries
@remote_menu("", "https://workflow.example.com", path="/workflow") # the remote names it
class Shell: ...

A non-blank label is the shell’s: it wins over the one the remote answers with (shellLabel). A blank one shows the path’s last segment until the remote answers with its own. path is where the remote’s screens live in this shell (Java’s @Menu field name): it travels as the option’s routePrefix, so the renderer knows the active section and the first breadcrumb on a cold load.

A record master opened from a listing offers ONE ”← Parent” link instead of the breadcrumb trail:

@ui("/customers/7")
@app("Customer", back_link=BackLink.PARENT)
class CustomerMaster: ...

The link goes to the nearest route above the app’s that resolves to a screen (/customers) and is labelled with that screen’s @title, else its last segment humanized — resolved on the server. An AppShell returned by an AppSupplier decides with its own back_link; a YAML shell with backLink: PARENT (its pageTitle: names the installed app when it has no title:). Java’s @App(backLink = PARENT).

To embed a remote view as an island inside a page, put a MicroFrontend in a component tree:

from mateu_ui.uidl.components import MicroFrontend
def component(self):
return MicroFrontend(base_url="https://billing.example.com", route="/invoices")

The island mounts its own mateu-ux against the remote backend and runs its own sync loop.

Resolved in the server. A micro frontend can also be resolved by this server while it builds the view (resolve = SERVER): the host asks the remote and embeds the answer, falling back to the browser asking when the remote is slow or down. Remotes are registered with add_mateu(remotes=…), and the same machinery fills content slots — holes for managed content a content service provides. See MicroFrontend: .NET and Python, ContentSlot: .NET and Python and the server options.

Adapting foreign classes (component adapters)

Section titled “Adapting foreign classes (component adapters)”

The ComponentAdapter SPI (Java’s ComponentAdapter<T>) renders a class that carries no Mateu markers and rebuilds it from the state:

from mateu_ui.uidl import AdaptedView, ComponentAdapter, ui
from mateu_ui.uidl import components as fluent
@ui("/order") # routing only: the adapter owns the UI
class Order: # a plain domain class
customer = "Ana"
def confirm(self): self.confirmed = True
class OrderAdapter(ComponentAdapter[Order]):
def type(self): return Order
def adapt(self, order):
return AdaptedView(
components=[fluent.FormField(field_id="customer", label="Customer"),
fluent.Button(label="Confirm", action_id="confirm")],
state={"customer": order.customer},
actions=["confirm"],
)
def deserialize(self, state):
order = Order()
if "customer" in state: order.customer = state["customer"]
return order

Put the adapter in a module you pass to add_mateu. A routed model renders through its adapter; a model held by a field of an ordinary form renders as an independent island with its own state and actions. Only the action ids the adapted view lists reach the model; returning None (or the model) re-renders it.

The lighter idiom still works when you control the screen: wrap the foreign object in a view — the mapper renders plain fields reflectively, and your actions write back:

@ui("/pedido")
class PedidoView: # Pedido is a third-party class you cannot touch
cliente: str = ""
importe: float = 0.0
def __init__(self):
self._pedido = pedido_repo.load()
self.cliente, self.importe = self._pedido.cliente, self._pedido.importe
@button()
def guardar(self):
self._pedido.cliente, self._pedido.importe = self.cliente, self.importe
pedido_repo.save(self._pedido)
return Message("Saved")

For full control of the UI, make the wrapper a ComponentTreeSupplier and emit a fluent tree.

The Python analogue of Java’s composed annotations needs no framework machinery at all: a reusable Annotated alias IS the semantic annotation — one domain word bundling markers —

ImporteTotal = Annotated[float, Money(), Label("Importe total")]
@ui("/invoice")
class Invoice:
total: ImporteTotal = 0.0 # behaves as Money() + Label(...) directly

and class/method decorators compose as plain functions:

def pantalla_compacta(cls):
return compact(read_only(cls))

@ai(sse="/ai/chat") on the @app class emits sseUrl in the app metadata; every renderer then shows the floating AI chat button. The endpoint is yours to implement — the chat panel POSTs

{ "message": "user text", "sessionId": "…", "menuContext": "… (first message only)" }

with Accept: text/event-stream (plus Authorization: Bearer … and X-Session-Id when available) and renders the streamed data: lines as the reply. Special data: payloads: a JSON {"event": "...", "detail": {...}} is re-dispatched on the client event bus (agent-error shows an error bubble), and a token-usage JSON updates the usage footer. A minimal FastAPI endpoint:

from fastapi.responses import StreamingResponse
@fastapi_app.post("/ai/chat")
async def chat(rq: dict):
async def stream():
async for chunk in my_agent.stream(rq["message"], rq.get("sessionId")):
yield f"data: {chunk}\n\n"
return StreamingResponse(stream(), media_type="text/event-stream")

Under PEP 649 annotations evaluate lazily and are no longer eagerly stored in __dict__['__annotations__']. Mateu reads them via inspect.get_annotations(...), so the field markers work on Python 3.11 through 3.14+.

YAML pages: the components this server builds

Section titled “YAML pages: the components this server builds”

A specs/ui/<route>.yaml page (or a routes.yaml entry’s layout:) is built from YAML by this server: every component of the fluent catalogue, read generically off its properties (the YAML keys are the component’s attributes, camel-cased), plus Form pages, partials and ComponentRef, and a type: Listing over a REST source (rowsSource, columns, filters, searchable, pageSize — the yaml starter’s products page; the renderer fetches the rows itself). A Button whose actionable: is a RouteLink navigates; a listing’s rowRoute opens a record page. A Form may fill a design-system page template (template: — Item overview, Welcome, Dashboard landing… laid out exactly as the Java server lays them out), and a type: AppShell definition bound to the mount route is served as the app shell (menus, flows, widgets, header switches, access: per caller — or declare the shell in code, an @app class or an AppSupplier). A definition-only page also reads its definition’s actions: (client-runnable flows and REST actions; proxied ones run through the server, ${secret.X} injected). An unknown type: renders as an “Unsupported component: <type>” text.

A YAML file under <specs>/partials/ is not a page but a partial — one component, or a content: list of them, usable anywhere a component is:

specs/ui/partials/address-block.yaml
content:
- type: FormField
id: street
label: Street
- type: FormField
id: city
label: City
# any page
- type: Partial
ref: address-block

A partial standing for several components is spliced into its parent’s content, not wrapped, so one inside a form yields form fields. Partials are resolved while the tree is built and never reach the wire. A missing ref costs the partial, not the page; a cycle is broken rather than followed.

When you drive the SyncHandler yourself instead of through add_mateu, a partial can also be registered in code, on the YAML loader the handler holds:

handler.yaml_specs.partials.register("legal-notice", [{"type": "Text", "text": "Prices include VAT."}])

Unlike the Java server, a ref here cannot name a class — the declarative form only. Full reference: Partials.

Routes can also be declared as data, in a routes.yaml next to the definitions under your specs directory (specs/ui/ by default, or MATEU_SPECS_DIR). An entry binds a definition (the layout), a viewModel and its parameters independently, so one screen can answer several routes with different parameters pinned:

routes:
- route: tickets/open
viewModel: myapp.views.Tickets
fixedParams:
status: open
- route: tickets/closed
viewModel: myapp.views.Tickets
fixedParams:
status: closed

Entries are merged over the decorator-declared views and win. Parameters resolve as fixed > client state > path > query > defaults — the same order as the Java server and the browser: a None in the client state is no value (the path, the URL’s query and the defaults still fill it), defaults only fill what nothing else supplied, and fixed ones are re-applied on the server over everything, including the state the client sends back.

Both viewModel and view_model are accepted — the file is the same one a Java or C# app consumes, but snake_case reads more naturally here.

See the full reference, including the JSON Schema for editor completion, in Route registry. Not available in this port: the static-bundle exporter, so nothing ships the table to a browser.

Required(), Min(n), Max(n), Length(min=, max=) and Pattern(regexp) in a field’s Annotated[...], @validation(condition, field_id, message) on the class and a ValidationSupplier travel as the component’s validations (the same conditions and messages Java emits), so the renderer refuses to submit an invalid form — and the same constraints are checked again on the server when a crud form is saved and in the import wizard’s report.

The length constraint is Length because in Java and C# Size is a component’s sizing intent.

A list[Row] field is a grid with a row editor: + / Edit open the row form beside the grid (DetailForm(position=, columns=) customises it), Save / Save and add another / Prev / Next / remove / move up / move down edit the rows held in the form state, saved with the form. InlineEditing() edits the cells in place instead (its + appends an empty row). Grids, textareas and rich text span the whole row of a multi-column form; Colspan(n) sets a span.

@wizard_completion_action("Book") on a wizard method: the penultimate step shows that button instead of Next; the last step becomes the read-only result screen, reached only through it.

csv_exportable(), excel_exportable() and pdf_exportable() on a Crud add Export CSV / Excel / PDF buttons (the whole filtered result set). Mateu ships no spreadsheet or PDF engine: CSV has a built-in writer, and Excel / PDF are written by a ListingExporter subclass of yours, in a module you register (it is discovered like the other suppliers and built with no arguments). It receives a ListingExport (format, title, columns, every filtered row, search text) and returns an ExportedFile (bytes, optional media type and filename). Without one, the Excel / PDF buttons are not offered. A starting point with openpyxl (your dependency, not Mateu’s):

import io
from openpyxl import Workbook
from mateu_ui.uidl import ExportedFile, ExportFormat, ListingExport, ListingExporter
class ExcelExporter(ListingExporter):
format = ExportFormat.EXCEL
def export(self, export: ListingExport) -> ExportedFile:
book = Workbook()
sheet = book.active
sheet.append([c.label for c in export.columns])
for row in export.rows:
sheet.append([c.text_of(row) for c in export.columns])
out = io.BytesIO()
book.save(out)
return ExportedFile(out.getvalue())

Catalogues: REST sources and business components

Section titled “Catalogues: REST sources and business components”

@rest_source("countries", url=…, value_path=…) on any app class, a RestSourceCatalogSupplier class, or specs/ui/sources.yaml declare a named endpoint once; surfaces reference it with RestOptions(source="countries"), @rest_listing(source=…), @rest_action(source=…), @rest_data(source=…). The catalogue rides the app metadata; proxy fetches resolve it on the server. A view assembled at runtime declares its proxy sources with RestSourceSupplier.

@business_component("AgencySelector") on a method returning a composition, a ComponentCatalogSupplier, or specs/ui/components.yaml declare a reusable composition; fluent.ComponentRef("AgencySelector") references it anywhere a component goes.

A field holding a routed view (documento: Annotated[Documento, Inline()]) mounts it as an independent sub-app: its own route, type, state and actions; the host passes context by setting fields on the value (they seed the island’s state). Inline() drops the island’s page chrome. A view action returning self re-renders it in place — that is how an island switches between its own server-decided states.

A specs/ui/<route>.yaml with viewModel: + layoutDelta: {order, hidden, overrides} re-applies the human’s decisions over the view model’s INFERRED layout on every request, so the screen keeps following its model.

Forms + sections + field types + validation, Crud[T] (list / detail / edit / new / save / delete), the @app shell + menu navigation, wizards, page decorations, tabs, stereotypes, KPIs, FABs, shortcuts, compact, the unsaved-changes guard, i18n, events, security scaffolding, and the UX-pattern components (MetricCard/Scoreboard/DashboardPanel/ResponsiveGrid, FoldoutLayout, HeroSection, EmptyState, Skeleton, Gantt) with the Dashboard/Foldout/ItemOverview/Welcome declarative archetypes, plus everything above. Over 950 tests cover this port, including the shared wire-conformance corpus (test_wire_conformance.py) as a HARD gate: every case must match the Java golden except an explicit allow-list of known Java-golden defects.