Registry /
web-framework / fastapi-users-db-beanie
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
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 2.899s · 61.1MB
glibcpy 3.10–3.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"]
)
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.
fixEnsure `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.
fixUpgrade `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.
fixVerify 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.
fixEnsure 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.