⚡ FastAPI Tutorial

Complete guide from basic setup to production-ready admin with authentication.
Learn Monglo's core features step by step.

1 Basic Setup

Get started with Monglo in just a few lines of code. This example shows automatic collection discovery and default UI setup.

📦 Step 1: Database Connection & Engine

Connect to MongoDB and create a Monglo engine with auto-discovery enabled:

Python
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.monglo_demo

app = FastAPI(title="Monglo Admin")

# Instantiate monglo engine
engine = MongloEngine(database=db, auto_discover=True)
💡 Key Point:

auto_discover=True automatically finds all MongoDB collections in your database and creates admin views for them.

🚀 Step 2: Initialize on Startup

Use FastAPI's startup event to initialize Monglo and setup the UI:

Python
@app.on_event("startup")
async def startup():
    
    # Seed example data
    await seed_database(db)
    
    # Initialize monglo engine
    await engine.initialize()
    
    # Setup monglo UI with custom branding
    setup_ui(
        app, 
        engine=engine,
        title="My Custom App",  # Custom title
    )
    
    # Setup monglo router
    app.include_router(create_fastapi_router(engine, prefix="/api"))
📌 What happens here:
  • seed_database() - Populates database with sample data (optional)
  • engine.initialize() - Discovers collections and detects relationships
  • setup_ui() - Adds admin UI routes at /admin
  • create_fastapi_router() - Adds REST API routes at /api

📄 Step 3: Complete Basic Example

Here's the full working application with all imports and shutdown handling:

app.py - Complete Basic Example
from fastapi import FastAPI
from motor.motor_asyncio import AsyncIOMotorClient

from monglo import MongloEngine
from monglo.ui_helpers.fastapi import setup_ui
from monglo.adapters.fastapi import create_fastapi_router
from db import seed_database

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.monglo_demo

app = FastAPI(title="Monglo Admin")

# Instantiate monglo engine
engine = MongloEngine(database=db, auto_discover=True)

@app.on_event("startup")
async def startup():
    
    # Seed example data
    await seed_database(db)
    
    # Initialize monglo engine
    await engine.initialize()
    
    # Setup monglo UI with custom branding
    setup_ui(
        app, 
        engine=engine,
        title="My Custom App",  # Custom title
    )
    
    # Setup monglo router
    app.include_router(create_fastapi_router(engine, prefix="/api"))

@app.on_event("shutdown")
async def shutdown():
    client.close()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
$ python app.py
INFO: Uvicorn running on http://0.0.0.0:8000
🚀 Admin UI: http://localhost:8000/admin
📡 REST API: http://localhost:8000/api

2 Advanced Configuration

For production apps, you'll want manual control over which collections are exposed and how they behave. Disable auto-discovery and register custom admin classes.

⚙️ Step 1: Disable Auto-Discovery

Python
# MongoDB connection
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.ecommerce_advanced

# Initialize Monglo engine
engine = MongloEngine(
    database=db,
    auto_discover=False  # Don't auto-discover - we'll register custom admins manually
)

🎨 Step 2: Custom UI Branding

Python
# Setup admin UI with branding
setup_ui(
    app,
    engine=engine,
    title="E-Commerce Admin",
    prefix="/custom_admin",
)

🔄 Step 3: Startup & Shutdown Events

Order matters! Setup custom admins BEFORE calling engine.initialize():

Python
# STARTUP & SHUTDOWN

@app.on_event("startup")
async def startup():
    """Initialize application on startup"""
    
    print("🚀 Starting E-Commerce Admin...")
    
    # Seed database with example data
    await seed_database(db)
    
    # Setup custom admin configurations FIRST
    await setup_admin(engine)
    
    # Then initialize monglo engine (discover relationships, etc.)
    await engine.initialize()
    
    # Setup REST API router
    app.include_router(
        create_fastapi_router(engine, prefix="/api"),
        prefix="/api",
        tags=["API"]
    )

3 Custom Admin Classes

Define custom ModelAdmin classes to control exactly how each collection appears and behaves in the admin UI.

👤 Example: User Admin

Python
class UserAdmin(ModelAdmin):
    """Custom admin for Users collection"""
    
    # Display name in sidebar
    display_name = "Users"
    
    # Fields to display in list view
    list_display = ["email", "full_name", "role", "is_active", "created_at"]
    
    # Fields to search
    search_fields = ["email", "username", "full_name"]
    
    # Default sort
    default_sort = [("created_at", -1)]  # Newest first
    
    # Items per page
    per_page = 20

📦 Example: Product & Category Admins

Python
class CategoryAdmin(ModelAdmin):
    """Custom admin for Categories"""
    
    display_name = "Categories"
    list_display = ["name", "slug", "icon"]
    search_fields = ["name", "slug"]
    default_sort = [("name", 1)]
    per_page = 50


class ProductAdmin(ModelAdmin):
    """Custom admin for Products with advanced config"""
    
    display_name = "Products"
    list_display = ["sku", "name", "price", "stock", "is_active", "is_featured"]
    search_fields = ["name", "sku", "description"]
    default_sort = [("created_at", -1)]
    per_page = 25

🔧 Registering Custom Admins

Create a setup function to register all your custom admin classes:

Python
async def setup_admin(engine: MongloEngine):
    """
    Configure custom admin classes for collections
    
    This function registers custom ModelAdmin classes that define:
    - Display names and icons
    - List view columns
    - Search fields
    - Default sorting
    - Pagination settings
    - Field schemas
    """
    
    # Register custom admin classes
    registry = engine.registry
    
    # Users
    registry.register("users", UserAdmin)
    
    # Categories  
    registry.register("categories", CategoryAdmin)
    
    # Products
    registry.register("products", ProductAdmin)
    
    # Orders
    registry.register("orders", OrderAdmin)
    
    # Reviews
    registry.register("reviews", ReviewAdmin)
    
    print("✅ Custom admin configurations registered")
    print(f"   - {len(registry._collections)} collections with custom admin")

4 Authentication

Secure your admin panel with MongoDB-based authentication. Users are stored in your database with hashed passwords and role-based access control.

🔐 Step 1: Create Auth Backend

Python
# Helper function for password verification (example)
def verify_password(plain_password: str, hashed_password: str) -> bool:
    import hashlib
    hashed = hashlib.sha256(plain_password.encode()).hexdigest()
    return hashed == hashed_password


# Setup MongoDB-based authentication backend
auth_backend = MongoDBAuthenticationBackend(
    secret_key="your-secret-key-change-in-production",  # Use env variable in production
    user_collection=db.users,                           # Your users collection
    username_field="email",                             # Field for username/email
    password_field="hashed_password",                   # Field for hashed password
    role_field="role",                                  # Field for user role
    admin_role="admin",                           # Required role for admin access
    password_verifier=verify_password                   # Your password verification function
)

🛡️ Step 2: Setup UI with Authentication

Python
# Setup admin UI with authentication
# NOTE: Must be called BEFORE @app.on_event("startup") to register middleware
setup_ui(
    app,
    engine,
    prefix="/admin",
    title="Secured Admin Panel",
    brand_color="#6366f1",
    auth_backend=auth_backend  # Pass the auth backend!
)
⚠️ Important:

setup_ui() must be called BEFORE the @app.on_event("startup") event to properly register authentication middleware.

🚀 Step 3: Startup Event

Python
@app.on_event("startup")
async def startup():
    """Initialize application"""
    
    print("🚀 Starting Monglo Auth Example...")
    
    # Seed database
    await seed_database(db)
    
    # Setup custom admin configurations
    await setup_admin(engine)
    
    # Initialize Monglo engine
    await engine.initialize()

🎉 What You Get:

  • ✅ Automatic login page at /admin
  • ✅ Session-based authentication with secure cookies
  • ✅ Role-based access control (only "admin" role can access)
  • ✅ Password hashing and verification
  • ✅ Automatic logout and session management

Ready to Build? 🚀

You now understand Monglo's core features from basic setup to production authentication.

View Full Examples Installation Guide