Skip to content

Application Reference

This page documents Quater, RouteGroup, AppConfig, CORSConfig, and __version__.

Prerequisites

Read Public API for the route model and Deployment for production settings.

python
from quater import AppConfig, CORSConfig, Quater, RouteGroup, __version__

Quater

Added in 0.1.0a1.

Application object that owns routes, config, middleware, lifespan hooks, state, and adapters.

python
Quater(
    *,
    name: str | None = None,
    config: AppConfig | None = None,
    debug: bool | None = None,
    security: SecurityMode | None = None,
    allowed_hosts: Iterable[str] | None = None,
    trusted_proxies: Iterable[str] | None = None,
    max_body_size: MaxBodySize | None = None,
    max_form_parts: int | None = None,
    max_form_field_size: MaxBodySize | None = None,
    max_file_size: MaxBodySize | None = None,
    upload_spool_size: MaxBodySize | None = None,
    max_tool_response_size: MaxBodySize | None = None,
    max_action_response_size: MaxBodySize | None = None,
    cors: CORSConfig | None = None,
    content_security_policy: str | None = None,
    mcp_docs_path: str | None = "/mcp/docs",
    mcp_allowed_origins: Iterable[str] | None = None,
    mcp_auth: Authenticate | None = None,
    mcp_audit: AuditHook | None = None,
    cli_auth: Authenticate | None = None,
    action_approval: ActionApproval | None = None,
    access_logger: AccessLogHook | None = None,
    docs_path: str | None = "/docs",
    openapi_path: str | None = "/openapi.json",
    request_id_header: str | None = "x-request-id",
) -> None
ParameterTypeDefaultDescription
namestr | NoneNoneApp name used in generated metadata.
configAppConfig | NoneNoneBase immutable config. Keyword overrides win.
debugbool | NoneNoneOverrides config.debug. Debug responses include exception details.
securitySecurityMode | NoneNoneOverrides config.security. Use "strict" for production.
allowed_hostsIterable[str] | NoneNoneOverrides accepted Host headers. Empty strict mode accepts local hosts only.
trusted_proxiesIterable[str] | NoneNoneProxy IPs or CIDR ranges trusted for forwarded headers.
max_body_sizeint | str | NoneNoneMaximum body size. Strings accept b, kb, mb, or gb.
max_form_partsint | NoneNoneMaximum number of form fields and file parts.
max_form_field_sizeint | str | NoneNoneMaximum size for one string form field.
max_file_sizeint | str | NoneNoneMaximum size for one uploaded file.
upload_spool_sizeint | str | NoneNonePer-file size before upload data rolls to disk.
max_tool_response_sizeint | str | NoneNoneMaximum MCP tool response body size.
max_action_response_sizeint | str | NoneNoneMaximum CLI action response body size.
corsCORSConfig | NoneNoneBrowser CORS policy.
content_security_policystr | NoneNoneAdds Content-Security-Policy in strict and relaxed modes.
mcp_docs_pathstr | None"/mcp/docs"Human MCP docs path. None disables the page.
mcp_allowed_originsIterable[str] | NoneNoneBrowser origins allowed for MCP requests.
mcp_authAuthenticate | NoneNoneSurface auth for MCP requests. Required when any route uses tool=True. Runs per MCP HTTP request and does not create a session.
mcp_auditAuditHook | NoneNoneReceives redacted MCP tool-call audit events.
cli_authAuthenticate | NoneNoneSurface auth for local and remote CLI actions. Required when any route uses cli=True.
action_approvalActionApproval | NoneNoneRequired when any tool/action uses needs_approval=True.
access_loggerAccessLogHook | NoneNoneReceives structured access events.
docs_pathstr | None"/docs"Swagger UI path. None disables the page.
openapi_pathstr | None"/openapi.json"OpenAPI JSON path. None disables the document.
request_id_headerstr | None"x-request-id"Request id header to read and write. None disables the response header.

Returns: None. Instantiate it and register routes on the object.

For list-like string settings such as allowed_hosts, trusted_proxies, and mcp_allowed_origins, pass an iterable of strings. Quater rejects a single plain string because Python would otherwise split it into characters.

Example:

python
from quater import Quater

app = Quater(allowed_hosts=["api.example.com"])


@app.get("/health")
async def health() -> dict[str, bool]:
    return {"ok": True}

Route decorators

get, post, put, patch, and delete call route() with a fixed method.

python
route(
    method: str,
    path: str,
    *,
    name: str | None = None,
    description: str | None = None,
    tool: bool = False,
    cli: bool = False,
    needs_approval: bool = False,
    auth: Authenticate | None = None,
    inject: ResourceMap | None = None,
    metadata: dict[str, Any] | None = None,
    before: Iterable[BeforeMiddleware] = (),
    after: Iterable[AfterMiddleware] = (),
    around: Iterable[AroundMiddleware] = (),
    exception_handlers: Iterable[ExceptionHandlerEntry] = (),
) -> Callable[[HandlerT], HandlerT]
ParameterTypeDefaultDescription
methodstrrequiredHTTP method for route() and add_route().
pathstrrequiredRoute path such as /orders/{order_id}.
namestr | NoneNoneOperation name. Defaults to the handler name.
descriptionstr | NoneNoneHuman description for docs, MCP tools, and CLI actions.
toolboolFalseExpose the route as an MCP tool.
cliboolFalseExpose the route as a CLI action.
needs_approvalboolFalseRequire approval before MCP or CLI execution.
authAuthenticate | NoneNoneRoute-level auth hook.
injectResourceMap | NoneNoneRequest resources injected into handler parameters.
metadatadict[str, Any] | NoneNoneExtra metadata for docs and extensions.
beforeIterable[BeforeMiddleware]()Middleware that can run before the handler.
afterIterable[AfterMiddleware]()Middleware that can adjust the response.
aroundIterable[AroundMiddleware]()Middleware that wraps the pipeline.
exception_handlersIterable[ExceptionHandlerEntry]()Route-specific exception handlers.

Common methods and properties

MemberReturnDescription
routestuple[RouteDefinition, ...]Registered route definitions. Treat entries as read-only metadata.
stateStateApp-level attribute container.
asgiASGIAdapterExplicit ASGI callable.
rsgiRSGIAdapterExplicit RSGI callable.
wsgiWSGIAdapterExplicit WSGI callable.
include(group)RouteGroupInclude a top-level group.
add_route(...)RouteDefinitionRegister a route without decorator syntax.
before_request(fn)fnRegister global before middleware.
after_response(fn)fnRegister global after middleware.
around_request(fn)fnRegister global around middleware.
exception_handler(exc_type)decoratorRegister a global exception handler.
on_startup(fn)fnRegister startup hook.
on_shutdown(fn)fnRegister shutdown hook.
startup()NoneCompile routes and run startup hooks.
shutdown()NoneRun shutdown hooks.
handle(request)ResponseHandle an in-process request.
validate_production()NoneCompile routes and run production safety checks.

Raises:

  • ImproperlyConfigured for invalid config, missing mcp_auth, missing cli_auth, missing action_approval, docs path conflicts, or reserved paths.
  • MiddlewareStateError when you register middleware after routes compile.
  • TypeError when include() receives a non-RouteGroup.

RouteGroup

Added in 0.1.0a1.

Compile-time group for related routes. Quater flattens groups when you include them.

python
RouteGroup(
    prefix: str = "",
    *,
    tags: Iterable[str] = (),
    auth: Authenticate | None = None,
    inject: ResourceMap | None = None,
    metadata: Mapping[str, Any] | None = None,
    before: Iterable[BeforeMiddleware] = (),
    after: Iterable[AfterMiddleware] = (),
    around: Iterable[AroundMiddleware] = (),
    exception_handlers: Iterable[ExceptionHandlerEntry] = (),
) -> None
ParameterTypeDefaultDescription
prefixstr""Prefix applied to child routes. Must start with / when set.
tagsIterable[str]()OpenAPI tags inherited by child routes.
authAuthenticate | NoneNoneGroup auth that runs before route auth.
injectResourceMap | NoneNoneResources inherited by child routes.
metadataMapping[str, Any] | NoneNoneMetadata inherited by child routes.
beforeIterable[BeforeMiddleware]()Before middleware inherited by routes.
afterIterable[AfterMiddleware]()After middleware inherited by routes.
aroundIterable[AroundMiddleware]()Around middleware inherited by routes.
exception_handlersIterable[ExceptionHandlerEntry]()Exception handlers inherited by routes.

Example:

python
from quater import Quater, RouteGroup

app = Quater()
orders = RouteGroup(prefix="/orders", tags=["orders"])


@orders.get("/{order_id}")
async def get_order(order_id: str) -> dict[str, str]:
    return {"order_id": order_id}


app.include(orders)

Raises:

  • ImproperlyConfigured when prefixes or paths are invalid.
  • ImproperlyConfigured when a group includes itself, is included twice, or is modified after inclusion.
  • TypeError when include() receives a non-RouteGroup.

AppConfig

Added in 0.1.0a1.

Immutable application configuration. Most apps pass keywords to Quater().

python
AppConfig(
    debug: bool = False,
    security: SecurityMode = "strict",
    allowed_hosts: tuple[str, ...] = (),
    trusted_proxies: tuple[str, ...] = (),
    max_body_size: int = 2097152,
    max_form_parts: int = 1000,
    max_form_field_size: int = 1048576,
    max_file_size: int = 2097152,
    upload_spool_size: int = 1048576,
    max_tool_response_size: int = 1048576,
    max_action_response_size: int = 1048576,
    cors: CORSConfig | None = None,
    content_security_policy: str | None = None,
    docs_path: str | None = "/docs",
    openapi_path: str | None = "/openapi.json",
    mcp_docs_path: str | None = "/mcp/docs",
    mcp_allowed_origins: tuple[str, ...] = (),
    request_id_header: str | None = "x-request-id",
)
FieldTypeDefaultDescription
debugboolFalseEnables detailed framework error responses.
securitySecurityMode"strict"Security header mode.
allowed_hoststuple[str, ...]()Accepted Host headers.
trusted_proxiestuple[str, ...]()Trusted proxy IPs and CIDR networks.
max_body_sizeint2097152Maximum request body size in bytes.
max_form_partsint1000Maximum number of form fields and file parts.
max_form_field_sizeint1048576Maximum size for one string form field.
max_file_sizeint2097152Maximum size for one uploaded file.
upload_spool_sizeint1048576Per-file size before upload data rolls to disk.
max_tool_response_sizeint1048576Maximum MCP tool response body size.
max_action_response_sizeint1048576Maximum CLI action response body size.
corsCORSConfig | NoneNoneBrowser CORS policy.
content_security_policystr | NoneNoneCSP header value.
docs_pathstr | None"/docs"Swagger UI path.
openapi_pathstr | None"/openapi.json"OpenAPI JSON path.
mcp_docs_pathstr | None"/mcp/docs"Human MCP docs path.
mcp_allowed_originstuple[str, ...]()Browser origins allowed for MCP.
request_id_headerstr | None"x-request-id"Request id header.

Quater reads limit defaults from QUATER_* environment variables when you use Quater() without an explicit config. Constructor keyword options override environment values.

List-like string fields are normalized to tuples and reject single plain strings. Raises ImproperlyConfigured for unsupported security modes, invalid paths, invalid header names, invalid size settings, invalid trusted proxies, empty CSP, or docs_path without openapi_path.

CORSConfig

Added in 0.1.0a1.

Browser CORS policy. CORS is not authentication.

python
CORSConfig(
    allowed_origins: tuple[str, ...],
    allowed_methods: tuple[str, ...] = ("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"),
    allowed_headers: tuple[str, ...] = (),
    expose_headers: tuple[str, ...] = (),
    allow_credentials: bool = False,
    max_age: int | None = None,
)
FieldTypeDefaultDescription
allowed_originstuple[str, ...]requiredBrowser origins allowed to read responses.
allowed_methodstuple[str, ...]common API methodsValid HTTP method tokens advertised during preflight.
allowed_headerstuple[str, ...]()Allowed request headers. Empty reflects sanitized requested headers.
expose_headerstuple[str, ...]()Response headers browser code may read.
allow_credentialsboolFalseWhether browsers may send credentials.
max_ageint | NoneNoneBrowser preflight cache seconds.

allowed_methods accepts standard methods and valid extension method tokens such as PROPFIND. If you expose a custom method with route("PROPFIND", ...) and browser clients call it cross-origin, add that method here too.

Raises ImproperlyConfigured for empty values, invalid method tokens, invalid header names, wildcard origins with credentials, or negative max_age.

version

Added in 0.1.0a1.

Installed Quater version.

python
from quater import __version__

print(__version__)

Expected output:

text
0.1.0a1

What Can Go Wrong

docs_path requires openapi_path : Disable both, or keep both enabled.

RouteGroup prefix must start with '/' : Use RouteGroup(prefix="/api").

CORS wildcard origins cannot be used with credentials : Use explicit origins when allow_credentials=True.

Production safety check failed: : Fix the listed production settings before serving traffic.

Also See

  • Public API: usage examples for these objects.
  • Security: host, CORS, and production defaults.
  • Deployment: server options and production checks.

Released under the MIT License.