ZCore LogoZCore
Api reference

BaseRouter

Comprehensive API reference for the BaseRouter class, RouteKey enumeration, lookup projections, schema introspection, custom route hooks, and endpoint overrides.

BaseRouter automatically scaffolds standard security-aware CRUD, search, lookup, and schema introspection endpoints (POST, GET, GET_ALL, SEARCH, LOOKUP, UPDATE, PATCH, DELETE, and SCHEMA) with primary key reflection, dependency injection, auto-bound anti-shadowing hooks, and hierarchical route specificity sorting.

Class Definition

from typing import Generic, TypeVar
from pydantic import BaseModel
from zcore import BaseRouter, RouteKey

CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)

class BaseRouter(Generic[CreateSchemaType, UpdateSchemaType]):
    def __init__(self) -> None:
        ...

Class Attributes

These attributes configure the scaffolded endpoints in your subclass:

Prop

Type


RouteKey Enumeration

The RouteKey enum identifies standard HTTP endpoints managed by BaseRouter:

from zcore import RouteKey

Prop

Type


Extension & Lifecycle Hooks

Subclasses can hook into the route registration lifecycle or trigger route sorting on demand:

register_custom_routes

A dedicated lifecycle hook executed at the end of standard route registration before the initial sorting sweep. Subclasses should override this method to attach custom domain endpoints without overriding __init__:

def register_custom_routes(self) -> None:
    @self.router.get("/summary")
    async def get_summary():
        return {"status": "ok"}

sort_routes

A public convenience wrapper that sorts all routes registered on self.router using hierarchical path specificity scoring:

def sort_routes(self) -> None:
    """Sort routes using hierarchical specificity scoring to avoid path shadowing."""
    self._sort_routes()

Dependency Methods

get_route_action

Retrieves the database/permission action name for a given route key using model.actions(). Returns an empty string for RouteKey.SCHEMA.

def get_route_action(self, route_key: RouteKey) -> str: ...
  • RouteKey.SCHEMA $\rightarrow$ ""
  • RouteKey.POST $\rightarrow$ model.actions().CREATE
  • RouteKey.GET $\rightarrow$ model.actions().VIEW
  • RouteKey.GET_ALL / RouteKey.SEARCH $\rightarrow$ model.actions().LISTVIEW
  • RouteKey.LOOKUP $\rightarrow$ model.actions().LOOKUP
  • RouteKey.UPDATE / RouteKey.PATCH $\rightarrow$ model.actions().UPDATE
  • RouteKey.DELETE $\rightarrow$ model.actions().DELETE

get_route_dependencies

Generates route dependencies. Defaults to [get_optional_user_stub] for RouteKey.SCHEMA to support optional authentication and guest masking, and [HasScopes(action)] for all standard CRUD and lookup operations.

def get_route_dependencies(self, route_key: RouteKey, action: str) -> list[Any]: ...

Prop

Type


Overridable Endpoint Handlers

Subclasses can override the core endpoint execution methods to customize response envelopes, inject custom query parameters, or set specialized HTTP status codes:

schema_endpoint

async def schema_endpoint(self, action: str | None = None) -> ResponseWrapper: ...

Resolves dynamic Pydantic V2 JSON schemas pruned according to active security context. Accepts an optional action parameter ("create", "update", "view", "lookup"). If omitted, returns a mapping of all configured resource schemas.

create_endpoint

async def create_endpoint(self, data_in: Any, service: BaseService) -> ResponseWrapper: ...

get_endpoint

async def get_endpoint(self, id: Any, service: BaseService) -> ResponseWrapper: ...

get_all_endpoint

async def get_all_endpoint(self, service: BaseService, pagination: Any = None) -> ResponseWrapper: ...

search_endpoint

async def search_endpoint(self, search_in: SearchRequest, service: BaseService) -> ResponseWrapper: ...

Automatically synchronizes the primary sort field and order from search_in.sort[0] into CursorParams when cursor pagination is active.

lookup_endpoint

async def lookup_endpoint(self, search_in: SearchRequest, service: BaseService) -> ResponseWrapper: ...

update_endpoint

async def update_endpoint(self, id: Any, data_in: Any, service: BaseService) -> ResponseWrapper: ...

patch_endpoint

async def patch_endpoint(self, id: Any, data_in: Any, service: BaseService) -> ResponseWrapper: ...

delete_endpoint

async def delete_endpoint(self, id: Any, service: BaseService, force: bool = False) -> ResponseWrapper: ...

Architectural Mechanisms

Intelligent Projection (_resolve_lookup_projections): When processing /lookup queries, BaseRouter introspects lookup_schema and maps declared properties directly to model column attributes. It builds a database load_only(*fields) projection, automatically incorporates the primary key, and configures relationship loaders (selectinload for collections, joinedload for scalars). Only attributes declared in the lookup schema are loaded from the database.

Auto-Sorting & Anti-Shadowing (_bind_router_sorting_hooks): In FastAPI, parameterized routes (such as /{id:uuid}) can accidentally intercept static routes (such as /summary, /search, or /_schema) if registered earlier, causing 422 RequestValidationError failures.

BaseRouter resolves this automatically:

  1. It sorts routes using hierarchical path specificity scoring so static path segments always precede dynamic parameters.
  2. In __init__, it executes _bind_router_sorting_hooks(), wrapping router.add_api_route and router.add_route. Any custom route registered later (in register_custom_routes() or child router constructors) triggers an automatic re-sort, guaranteeing that custom endpoints are never shadowed.

On this page