API Reference
Package exports
AdminSite, ModelAdmin, FieldWidget, site, display, and action
are re-exported from submodules for convenience; their API is documented in the
sections below.
FastAPI Mongo Admin — Django-inspired admin for MongoDB.
- fastapi_mongo_admin.mount_admin_app(app, get_database, *, admin_site=None, router_prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, api_write_methods=False)[source]
Mount the admin UI, JSON API, and static files on a FastAPI application.
- Parameters:
app (FastAPI) – FastAPI application to extend.
get_database (Callable[[...], AsyncIOMotorDatabase | Database | Awaitable[AsyncIOMotorDatabase]]) – Callable returning a Motor database, PyMongo database, or awaitable that resolves to one.
admin_site (AdminSite | None) – Admin site registry. Defaults to the global
sitesingleton.router_prefix (str) – URL prefix for admin routes (default
/admin).mode (Literal['async', 'sync']) – MongoDB access mode —
async(Motor) orsync(PyMongo).auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency injected on admin routes.
permission_dependency (Callable[[...], Any] | None) – Optional dependency checked before the admin index.
api_write_methods (bool) – When
True, registerPOST,PUT,PATCH, andDELETEJSON API routes and include them in OpenAPI (/docs). WhenFalse(default), onlyGETlist/detail routes are registered and documented.
- Returns:
None. Mutates
appby including the admin router and static mount.- Return type:
None
- fastapi_mongo_admin.create_admin_router(admin_site, get_database, *, prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, static_url='/admin/static', api_write_methods=False)[source]
Create the admin UI and JSON API router.
- Parameters:
admin_site (AdminSite) – Registered models and global admin configuration.
get_database (Callable[[...], Any]) – Callable returning the MongoDB database (sync or async).
prefix (str) – URL prefix for all admin routes (default
/admin).mode (Literal['async', 'sync']) – MongoDB access mode —
asyncorsync.auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency for authentication.
permission_dependency (Callable[[...], Any] | None) – Optional dependency checked on the admin index.
static_url (str) – URL path prefix for packaged admin static files.
api_write_methods (bool) – When
True, exposePOST,PUT,PATCH, andDELETEJSON API endpoints in the router and OpenAPI schema. WhenFalse(default), onlyGETendpoints are registered.
- Returns:
APIRouter with HTML admin views and
/apiJSON routes included.- Return type:
Admin registry
AdminSite registry.
- class fastapi_mongo_admin.admin.site.AdminSite(name='admin', template_dirs=None)[source]
Registry for models and custom admin views.
- register(model_or_iterable, admin_class=None, **options)[source]
Register one or more Pydantic models with optional admin class.
- Parameters:
model_or_iterable (Type[BaseModel] | Iterable[Type[BaseModel]]) – A single model class or iterable of models.
admin_class (type[ModelAdmin] | None) – Optional
ModelAdminsubclass; defaults toModelAdmin.**options (Any) – ModelAdmin options applied before registration (e.g.
collection_name,list_display).
- Returns:
None.
- Raises:
ValueError – When
collection_nameis missing or already registered.- Return type:
None
- register_view(name, path, endpoint, *, permission=None)[source]
Register a custom admin page.
- Parameters:
- Returns:
None.
- Return type:
None
- get_model_admin(collection_name)[source]
Return the ModelAdmin registered for a collection.
- Parameters:
collection_name (str) – MongoDB collection name.
- Returns:
ModelAdmin instance or
Nonewhen not registered.- Return type:
ModelAdmin | None
ModelAdmin base class with Django-admin-style hooks.
- class fastapi_mongo_admin.admin.model.ModelAdmin(model=None)[source]
Configuration and hooks for a registered Pydantic model.
Subclass to customize changelist columns, filters, forms, permissions, and document lifecycle behavior.
- get_model_name()[source]
Return the human-readable model name.
- Returns:
Model class name, or
collection_namewhen no model is set.- Return type:
- get_model_name_plural()[source]
Return the plural human-readable model name.
- Returns:
Pluralized model label for result counts and bulk messages.
- Return type:
- get_list_display_links(request=None)[source]
Return changelist columns that link to the change form.
- get_sortable_field(column_name)[source]
Return the database field used to sort a changelist column.
- get_formfield_overrides(request=None, obj=None)[source]
Return per-field widget overrides for the change form.
- formfield_for_field(field, request=None, obj=None)[source]
Customize a single form field after defaults and overrides.
- get_list_filters(request=None, params=None)[source]
Instantiate sidebar list filters from configuration.
- get_queryset(request, base_query)[source]
Customize the base MongoDB query for changelist operations.
- async save_model(request, obj, form_data, is_new)[source]
Hook called before persisting a document.
- Parameters:
- Returns:
Data dict to write to MongoDB.
- Return type:
- has_view_permission(request, user=None, obj=None)[source]
Return whether the user can view the changelist and detail pages.
- has_change_permission(request, user=None, obj=None)[source]
Return whether the user can change documents.
- has_delete_permission(request, user=None, obj=None)[source]
Return whether the user can delete documents.
- get_date_format()[source]
Return the strftime-style format for date display.
- Returns:
Custom format string, or
Nonefor the default8 Apr 2026.- Return type:
str | None
- get_datetime_format()[source]
Return the strftime-style format for datetime display.
- Returns:
Custom format string, or
Nonefor the default8 Apr 2026, 7:32pm.- Return type:
str | None
- boolean_display_cell(field_name, obj, *, true_label, false_label)[source]
Return colored-label metadata for a boolean changelist cell.
- format_display_value(field_name, value)[source]
Apply date/datetime display formatting when applicable.
Decorators
Decorators for ModelAdmin display columns and actions.
- fastapi_mongo_admin.admin.decorators.display(description=None, ordering=None)[source]
Mark a ModelAdmin method as a changelist display column.
Actions
Admin action helpers.
- async fastapi_mongo_admin.admin.actions.run_delete_selected(model_admin, request, repo, docs, doc_ids)[source]
Delete selected documents after calling
delete_modelhooks.- Parameters:
- Returns:
Number of documents deleted from the database.
- Return type:
List filters
Base list filter classes.
- class fastapi_mongo_admin.admin.filters.base.ListFilter(request, params, model_admin, field_name)[source]
Base class for changelist sidebar filters.
- Parameters:
request (Request | None)
model_admin (ModelAdmin)
field_name (str)
Choice list filter.
- class fastapi_mongo_admin.admin.filters.choice.ChoiceListFilter(request, params, model_admin, field_name)[source]
Filter by discrete choice values.
- Parameters:
request (Request | None)
model_admin (ModelAdmin)
field_name (str)
Boolean list filter.
- class fastapi_mongo_admin.admin.filters.boolean.BooleanFieldListFilter(request, params, model_admin, field_name)[source]
Filter boolean fields with Yes/No choices.
- Parameters:
request (Request | None)
model_admin (ModelAdmin)
field_name (str)
Date list filter and date hierarchy.
- class fastapi_mongo_admin.admin.filters.date.DateFieldListFilter(request, params, model_admin, field_name)[source]
Filter documents by common date ranges.
- Parameters:
request (Request | None)
model_admin (ModelAdmin)
field_name (str)
- fastapi_mongo_admin.admin.filters.date.build_date_hierarchy_query(field, year, month, day)[source]
Build a date hierarchy drill-down query.
Filter by related document ObjectId.
- Parameters:
request (Request | None)
model_admin (ModelAdmin)
field_name (str)
Return related-document lookup choices.
Field widgets
Widget type constants and per-field override configuration.
- fastapi_mongo_admin.admin.fields.widgets.is_primitive_list(annotation)[source]
Return whether an annotation is a list of primitive scalar values.
- fastapi_mongo_admin.admin.fields.widgets.widget_for_type(field_type, *, has_choices=False, annotation=None)[source]
Map an inferred field type to an HTML widget name.
- fastapi_mongo_admin.admin.fields.widgets.step_for_type(field_type)[source]
Return the HTML
stepattribute for numeric field types.
- class fastapi_mongo_admin.admin.fields.widgets.FieldWidget(widget=None, attrs=<factory>)[source]
Override default widget and HTML attributes for a model field.
- fastapi_mongo_admin.admin.fields.widgets.apply_field_widget_override(admin_field, override)[source]
Apply a widget override onto an
AdminField.- Parameters:
admin_field (Any) –
AdminFieldinstance to mutate.override (FieldWidget | dict[str, Any]) –
FieldWidgetor shorthand dict.
- Returns:
None.
- Return type:
None
Mount helpers
Mount helpers for FastAPI applications.
- fastapi_mongo_admin.utils.get_static_directory()[source]
Return the packaged static assets directory.
- Returns:
Path to the
fastapi_mongo_admin/staticpackage directory.- Return type:
- fastapi_mongo_admin.utils.mount_admin_app(app, get_database, *, admin_site=None, router_prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, api_write_methods=False)[source]
Mount the admin UI, JSON API, and static files on a FastAPI application.
- Parameters:
app (FastAPI) – FastAPI application to extend.
get_database (Callable[[...], AsyncIOMotorDatabase | Database | Awaitable[AsyncIOMotorDatabase]]) – Callable returning a Motor database, PyMongo database, or awaitable that resolves to one.
admin_site (AdminSite | None) – Admin site registry. Defaults to the global
sitesingleton.router_prefix (str) – URL prefix for admin routes (default
/admin).mode (Literal['async', 'sync']) – MongoDB access mode —
async(Motor) orsync(PyMongo).auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency injected on admin routes.
permission_dependency (Callable[[...], Any] | None) – Optional dependency checked before the admin index.
api_write_methods (bool) – When
True, registerPOST,PUT,PATCH, andDELETEJSON API routes and include them in OpenAPI (/docs). WhenFalse(default), onlyGETlist/detail routes are registered and documented.
- Returns:
None. Mutates
appby including the admin router and static mount.- Return type:
None
Router
Admin view routes.
- fastapi_mongo_admin.views.router.create_admin_router(admin_site, get_database, *, prefix='/admin', mode='async', auth_dependency=None, permission_dependency=None, static_url='/admin/static', api_write_methods=False)[source]
Create the admin UI and JSON API router.
- Parameters:
admin_site (AdminSite) – Registered models and global admin configuration.
get_database (Callable[[...], Any]) – Callable returning the MongoDB database (sync or async).
prefix (str) – URL prefix for all admin routes (default
/admin).mode (Literal['async', 'sync']) – MongoDB access mode —
asyncorsync.auth_dependency (Callable[[...], Any] | None) – Optional FastAPI dependency for authentication.
permission_dependency (Callable[[...], Any] | None) – Optional dependency checked on the admin index.
static_url (str) – URL path prefix for packaged admin static files.
api_write_methods (bool) – When
True, exposePOST,PUT,PATCH, andDELETEJSON API endpoints in the router and OpenAPI schema. WhenFalse(default), onlyGETendpoints are registered.
- Returns:
APIRouter with HTML admin views and
/apiJSON routes included.- Return type:
Repository
Collection repository for CRUD operations.
Return a human-readable label for a related document.
- class fastapi_mongo_admin.services.repository.CollectionRepository(backend, model_admin)[source]
Repository wrapping sync or async MongoDB backends for one collection.
- Parameters:
backend (Backend)
model_admin (ModelAdmin)
- async list_documents(*, page=1, search='', filter_params=None, date_hierarchy_params=None, show_all=False, request=None)[source]
List documents with pagination, search, and filters.
- Parameters:
page (int) – Page number (1-based).
search (str) – Changelist search string.
filter_params (dict[str, str] | None) – Active list-filter query parameters.
date_hierarchy_params (dict[str, str] | None) – Optional date hierarchy drill-down params.
show_all (bool) – When
True, uselist_max_show_allas page size.request (Any) – Current request passed to queryset hooks.
- Returns:
Dict with
results,total,page,per_page, andnum_pageskeys.- Return type:
- async get_document(doc_id)[source]
Fetch a single serialized document by id.
- Parameters:
doc_id (str) – Document id string.
- Returns:
Serialized document dict with an
idfield.- Raises:
DocumentNotFoundError – When no document matches the id.
- Return type:
- async update_document(doc_id, form_data, request=None)[source]
Update a document from form or JSON data.
Fetch the current value label for
list_select_relatedform fields.
Search related documents for a searchable form dropdown.
- Parameters:
- Returns:
List of
(value, label)tuples sorted by label.- Return type:
Register a backend for
list_select_relatedlookups.- Parameters:
collection (str) – Related collection name.
backend (AsyncMotorBackend | SyncPyMongoBackend) – Backend for that collection.
- Returns:
None.
- Return type:
None
Formatting
Display formatting for date and datetime values.
- fastapi_mongo_admin.formatting.parse_datetime(value)[source]
Parse a datetime from BSON, ISO string, or date.
- fastapi_mongo_admin.formatting.parse_date(value)[source]
Parse a date from BSON, ISO string, or datetime.
- fastapi_mongo_admin.formatting.format_date_display(value, fmt=None)[source]
Format a value for date display in lists and readonly fields.
Schema utilities
Pydantic schema inference for admin forms and lists.
- fastapi_mongo_admin.schemas.inference.serialize_document(doc)[source]
Convert a MongoDB document to a JSON-serializable dict.
- fastapi_mongo_admin.schemas.inference.prepare_for_mongodb(value)[source]
Recursively convert Python values to BSON-encodable types.
- fastapi_mongo_admin.schemas.inference.format_field_value(field)[source]
Format a field value for HTML form controls.
- Parameters:
field (AdminField) –
AdminFieldwithvalueand widget metadata.- Returns:
Value formatted for the field’s widget type.
- Return type:
- fastapi_mongo_admin.schemas.inference.infer_admin_fields(model, *, readonly_fields=None, choices=None, field_overrides=None)[source]
Build an
AdminFieldlist from a Pydantic model.- Parameters:
- Returns:
List of
AdminFieldmetadata objects.- Return type:
list[AdminField]
- fastapi_mongo_admin.schemas.inference.prepare_form_fields(model, *, obj=None, readonly_fields=None, choices=None, field_overrides=None, display_formatter=None)[source]
Build admin fields with values formatted for HTML widgets.
- Parameters:
obj (dict[str, Any] | None) – Existing document for edit forms.
readonly_fields (list[str] | None) – Field names rendered read-only.
choices (dict[str, list[tuple[Any, str]]] | None) – Per-field select choices.
field_overrides (dict[str, FieldWidget | dict[str, Any]] | None) – Per-field widget overrides.
display_formatter (Any | None) – Optional object with
format_display_value.
- Returns:
List of
AdminFieldobjects withvaluepopulated.- Return type:
list[AdminField]
- fastapi_mongo_admin.schemas.inference.infer_schema_dict(model)[source]
Return schema metadata dict for API responses.
Form parsing and Pydantic validation.
- fastapi_mongo_admin.schemas.forms.parse_form_to_model(model, form_data, *, existing=None, readonly_fields=None)[source]
Validate and normalize form or JSON data through a Pydantic model.
- Parameters:
- Returns:
Validated document dict from
model.model_dump().- Raises:
AdminValidationError – When Pydantic validation fails.
- Return type:
Field mapping
Field mapping between Pydantic model and MongoDB.
- fastapi_mongo_admin.services.mapping.translate_to_db(data, mapping)[source]
Translate model field keys to database keys.
- fastapi_mongo_admin.services.mapping.translate_from_db(doc, mapping)[source]
Translate database keys to model field keys.
Exceptions
Admin HTTP exceptions.
- exception fastapi_mongo_admin.exceptions.AdminException(status_code, detail, error_code=None, details=None)[source]
Base exception for admin operations.
- error_code
Optional machine-readable error code.
- details
Optional extra error context.
- exception fastapi_mongo_admin.exceptions.DocumentNotFoundError(document_id, collection_name)[source]
Raised when a document is not found in a collection.
- exception fastapi_mongo_admin.exceptions.CollectionNotFoundError(collection_name)[source]
Raised when a collection is not registered or missing.
- Parameters:
collection_name (str)
- exception fastapi_mongo_admin.exceptions.InvalidQueryError(detail, query=None)[source]
Raised when a changelist or API query is invalid.
Internationalization
Translation helper for admin UI.
- class fastapi_mongo_admin.i18n.translator.Translator(language, messages, fallback)[source]
Lookup translated strings with optional format placeholders.