FastAPI Users Beanie DB Adapter
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.
Warnings
- breaking Version 5.0.0 drops support for Python 3.9 and Beanie versions older than 2.0. Ensure your environment meets these requirements.
- breaking Versions 4.0.0 and 3.0.0 dropped support for Python 3.8 and 3.7 respectively. Older Python versions are no longer supported.
- breaking In 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.
- gotcha Beanie 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`.
- deprecated The 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.
Install
-
pip install fastapi-users-db-beanie
Imports
- BeanieBaseUser
from fastapi_users.db import BeanieBaseUser
- BeanieUserDatabase
from fastapi_users.db import BeanieUserDatabase
- Document
from beanie import Document
- PydanticObjectId
from beanie import PydanticObjectId
Quickstart
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"]
)