Registry / web-framework / fastapi-users-db-beanie

fastapi-users-db-beanie

JSON →
library5.0.0pypypi✓ verified 86d ago

FastAPI Users database adapter for Beanie ODM, providing tools to integrate user management with MongoDB databases. It leverages Beanie, an asynchronous Object-Document Mapper built on Pydantic and Motor. The library is currently at version 5.0.0 and is in maintenance mode, focusing on security updates and dependency maintenance, with no new features planned.

pip install fastapi-users-db-beanie
INSTALL
IMPORT
SIG · FASTAPI-USERS-DB-B
F
fastapi-users-db-beanie
web-frameworkpythonv5.0.0
Install
6.8s avg
Import
2827ms
Disk
62MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v5.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 2.899s · 61.1MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 6.8s · import 2.754s · 62MB
62MB installed
● package 62MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

BeanieBaseUser
from fastapi_users.db import BeanieBaseUser
BeanieUserDatabase
from fastapi_users.db import BeanieUserDatabase
Document
from beanie import Document
from fastapi_users.db import BeanieBaseUser # when not inheriting Document
Since v2.0.0, BeanieBaseUser is a mixin and must explicitly inherit from beanie.Document.
PydanticObjectId
from beanie import PydanticObjectId
from beanie import ObjectId
BeanieBaseUser only supports PydanticObjectId as the ID type since v2.0.0.

This quickstart demonstrates how to integrate `fastapi-users-db-beanie` with FastAPI Users and Beanie. It sets up a MongoDB connection, defines a `User` model inheriting from `BeanieBaseUser` and `beanie.Document`, and provides a dependency for `BeanieUserDatabase`. The FastAPI app includes authentication and user management routers, ensuring Beanie is initialized on startup.

import os from typing import AsyncGenerator import motor.motor_asyncio from beanie import Document, init_beanie, PydanticObjectId from fastapi import Depends, FastAPI from fastapi_users import FastAPIUsers, schemas from fastapi_users.authentication import BearerTransport, AuthenticationBackend from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase # --- Beanie/MongoDB Setup --- DATABASE_URL = os.environ.get('MONGODB_URL', 'mongodb://localhost:27017') client = motor.motor_asyncio.AsyncIOMotorClient( DATABASE_URL, uuidRepresentation="standard" ) db = client[os.environ.get('MONGODB_DB_NAME', 'database_name')] class User(BeanieBaseUser[PydanticObjectId], Document): # You can add custom fields here pass class UserRead(schemas.BaseUser[PydanticObjectId]): pass class UserCreate(schemas.BaseUserCreate): pass class UserUpdate(schemas.BaseUserUpdate): pass async def get_user_db() -> AsyncGenerator[BeanieUserDatabase, None]: yield BeanieUserDatabase(User) # --- FastAPI Users Setup --- bearer_transport = BearerTransport(tokenUrl="auth/jwt/login") def get_jwt_strategy(): SECRET = os.environ.get('AUTH_SECRET', 'YOUR_SUPER_SECRET_KEY') # CHANGE THIS IN PRODUCTION! return AuthenticationBackend( name="jwt", transport=bearer_transport, get_user_token_data=UserRead, # Or your custom token data schema secret=SECRET, lifetime_seconds=3600 ) fastapi_users = FastAPIUsers( get_user_db, [get_jwt_strategy()], UserRead, UserCreate, UserUpdate ) # --- FastAPI App --- app = FastAPI() @app.on_event("startup") async def on_startup(): await init_beanie( database=db, document_models=[User] ) app.include_router( fastapi_users.get_auth_router(get_jwt_strategy()), prefix="/auth/jwt", tags=["auth"] ) app.include_router( fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"] ) app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"] )
Debug
Known issues
breakingVersion 5.0.0 drops support for Python 3.9 and Beanie versions older than 2.0. Ensure your environment meets these requirements.
fix
Upgrade Python to 3.10+ and Beanie to 2.0+ before upgrading this package.
affects: >=5.0.0
breakingVersions 4.0.0 and 3.0.0 dropped support for Python 3.8 and 3.7 respectively. Older Python versions are no longer supported.
fix
Upgrade Python to 3.10+ for compatibility with the latest versions.
affects: >=3.0.0
breakingIn version 2.0.0, `BeanieBaseUser` and `BeanieBaseAccessToken` became pure mixins and no longer automatically inherit from `beanie.Document`. You must explicitly inherit from `Document` when defining your user model. Additionally, `BeanieBaseUser` now only supports `PydanticObjectId` as the ID type.
fix
Update your User model definition to `class User(BeanieBaseUser[PydanticObjectId], Document): ...`
affects: >=2.0.0
gotchaBeanie database initialization (`init_beanie`) must occur before any database operations are attempted. This is typically done in FastAPI's `startup_event` handler or using an `async_context_manager` for the app's `lifespan`.
fix
Ensure `await init_beanie(database=db, document_models=[YourUserModel])` is called during application startup.
affects: All
deprecatedThe documentation currently instructs users to use `motor.motor_asyncio.AsyncIOMotorClient` for MongoDB connections. However, `pymongo 4.16+` now includes a native asynchronous client, suggesting `motor` might eventually be replaced or become less recommended.
fix
While `motor` still works, be aware of potential future changes in recommended connection methods as PyMongo's native async client matures. Monitor Beanie and FastAPI Users documentation for updates.
affects: All
Errors
Common errors & fixes
ImportError: cannot import name 'BeanieUserDatabase' from 'fastapi_users.db'
The `BeanieUserDatabase` class (and often `BeanieBaseUser`) is not directly exposed from `fastapi_users.db` in recent versions of `fastapi-users`, or the `fastapi-users` package was installed without the necessary `[beanie]` extra.
fix
Ensure `fastapi-users` is installed with the `beanie` extra using `pip install 'fastapi-users[beanie]'` and import `BeanieUserDatabase` and `BeanieBaseUser` directly from `fastapi_users_db_beanie`.
TypeError: <class 'fastapi_users_db_beanie.BeanieBaseUser'> cannot be parametrized because it does not inherit from typing.Generic
This error occurs when attempting to use type parametrization (e.g., `BeanieBaseUser[PydanticObjectId]`) with an older version of `fastapi-users-db-beanie` where `BeanieBaseUser` was not defined as a generic type.
fix
Upgrade `fastapi-users` and `fastapi-users-db-beanie` to their latest compatible versions. The current versions support generic `BeanieBaseUser` which also inherits from `beanie.Document`.
AttributeError: type object 'YourUserModel' has no attribute 'email'
This typically means that the `User` model (or any other Beanie `Document` model) is not correctly defined, or it hasn't been properly registered with `beanie.init_beanie`, preventing Beanie from recognizing its fields during database operations or object instantiation.
fix
Verify that your custom `User` model correctly inherits from `fastapi_users_db_beanie.BeanieBaseUser` and `beanie.Document`, and that all fields are explicitly defined. Ensure that `beanie.init_beanie` is called during application startup with your `User` model included in the `document_models` list.
Pydantic validation error: Field required [type=missing
This Pydantic validation error indicates that data being processed by a Beanie `Document` model is missing a field that is defined as non-optional in the model, either during document creation or when loading data from MongoDB that doesn't conform to the model's schema.
fix
Ensure that all required fields are provided when creating or updating documents. If a field can be optional, declare it using `Optional[type]` (e.g., `email: Optional[str]`) or provide a `default` value in your Beanie `Document` model.
Upgrade
Version history
5.0.0latest on PyPI · released Nov 23, 2025
Audit
Dependencies
fastapi-usersrequiredCore user management library, this package is an adapter for it.
beanierequiredAsynchronous MongoDB ODM. Requires Beanie >=2.0 for v5.0.0 of this adapter.
motorrequiredAsynchronous MongoDB driver, used by Beanie for database interactions.
Agent activity
25 hits · last 30 days
node
22
Amazon
1
OpenAI (training)
1
Resources
fastapi-users-db-beanie — pip install fastapi-users-db-beanie · libregistry