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

fastapi-users-db-beanie

JSON →
library5.0.0pypypi✓ verified 35d 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.

web-frameworkdatabaseauth-security
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.

from fastapi_users.db import BeanieBaseUser
from fastapi_users.db import BeanieUserDatabase

Since v2.0.0, BeanieBaseUser is a mixin and must explicitly inherit from beanie.Document.

from beanie import Document

BeanieBaseUser only supports PydanticObjectId as the ID type since v2.0.0.

from beanie import PydanticObjectId

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 footguns
breakingVersion 5.0.0 drops support for Python 3.9 and Beanie versions older than 2.0. Ensure your environment meets these requirements.
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.
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.
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`.
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.
Upgrade
Version history

Breaking-change detection hasn't run for this library yet.

Audit
Security & dependencies

CVE tracking and dependency tree are planned for a later release.

Agent activity
16 hits · last 30 days
dotbot
4
gptbot
4
ahrefsbot
4
amazonbot
3
script
1
Resources