Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tutosrive/fastapi-CRUD-MongoDB/llms.txt

Use this file to discover all available pages before exploring further.

FastAPI CRUD MongoDB is a lightweight REST API starter that demonstrates full create, read, update, and delete operations over two resources — Users and Tasks — using the modern Python web framework FastAPI, the official MongoDB driver PyMongo, and Pydantic for data validation. The project is designed to be simple and readable, making it an ideal reference for developers learning how to wire FastAPI to a MongoDB backend without the overhead of an ODM like Beanie or MongoEngine.
MongoDB must be installed and running locally before starting the server. The application connects to the default host localhost on port 27017 with no authentication required. Download MongoDB Community Edition at mongodb.com/try/download/community.

Resources

The API manages two top-level resources, each backed by its own MongoDB collection.

User

Defined in app/models/user.py using Pydantic’s BaseModel:
FieldTypeRequiredDescription
idstringNoMongoDB ObjectId serialised as a string. Auto-assigned on creation.
namestringYesDisplay name of the user.
ageintegerYesAge of the user.
emailstringYesEmail address of the user.

Task

Defined in app/models/task.py. A separate TaskUpdate model makes every field optional so partial updates are safe:
FieldTypeRequiredDefaultDescription
idstringNoMongoDB ObjectId serialised as a string.
titlestringYesShort title of the task.
descriptionstringYesDetailed description of the task.
completedbooleanNofalseWhether the task has been completed.
created_bystringYesName or identifier of the task owner.

Project Layout

fastapi-CRUD-MongoDB/
├── main.py                  # FastAPI app factory and router registration
├── requirements.txt         # Pinned dependencies
└── app/
    ├── config/
    │   ├── db.py            # PyMongo MongoClient connection
    │   └── docs.py          # OpenAPI tag metadata (api_tags)
    ├── models/
    │   ├── user.py          # User Pydantic model
    │   └── task.py          # Task and TaskUpdate Pydantic models
    ├── schemas/
    │   ├── user.py          # user_entity / users_entity serialisers
    │   └── task.py          # task_entity / tasks_entity / task_update_entity serialisers
    ├── controllers/
    │   ├── user.py          # UserController — business logic + DB calls
    │   └── task.py          # TaskController — business logic + DB calls
    └── routes/
        ├── home.py          # GET / welcome endpoint
        ├── user.py          # /users CRUD router
        └── task.py          # /tasks CRUD router
  • config/ — infrastructure concerns: the database connection and OpenAPI metadata live here, keeping them separate from application code.
  • models/ — Pydantic models that serve as both request bodies and response schemas. FastAPI uses these for automatic validation and serialisation.
  • schemas/ — plain functions that convert raw MongoDB documents (which use _id) into API-friendly dicts (which use id).
  • controllers/ — the business-logic layer. Routes delegate all database interaction to controller classes, keeping route handlers thin.
  • routes/APIRouter instances grouped by tag. Each router is registered in main.py via app.include_router(...).

Application Entry Point

main.py creates the FastAPI application, wires the OpenAPI metadata, and registers all three routers:
from fastapi import FastAPI

from app.routes.home import home_router
from app.routes.user import user_router
from app.routes.task import task_router
from app.config.docs import api_tags

app = FastAPI(
    title='FASTAPI + MongoDB',
    description='Learning FastAPI with MongoDB ...',
    version='2025.0.1.0',
    openapi_tags=api_tags
)

app.include_router(home_router)
app.include_router(user_router)
app.include_router(task_router)
api_tags is defined in app/config/docs.py and provides human-readable descriptions for each tag group shown in the interactive docs:
api_tags = [
    {
        'name': 'User',
        'description': 'The user CRUD'
    },
    {
        'name': 'Task',
        'description': 'The tasks CRUD'
    }
]

Database Connection

app/config/db.py initialises a PyMongo MongoClient with no arguments, which connects to localhost:27017 by default:
from pymongo import MongoClient

mong_conn = MongoClient()
Controllers import mong_conn directly and access collections through it — for example, mong_conn.local.user for the users collection and mong_conn.local.task for tasks. Both collections live in MongoDB’s built-in local database.

Interactive API Documentation

FastAPI automatically generates two interactive documentation UIs at runtime — no extra configuration required:
UIURLDescription
Swagger UI/docsTry every endpoint directly from the browser.
ReDoc/redocClean, read-only reference layout.
Both UIs are powered by the OpenAPI schema that FastAPI derives from your Pydantic models and route definitions.

Dependencies

The project intentionally keeps its dependency footprint minimal:
PackageVersionPurpose
fastapi[standard]0.122.0Web framework, validation, and OpenAPI support.
pymongo4.15.4Official MongoDB driver for Python.
fastapi[standard] bundles Pydantic v2, Starlette, and Uvicorn so no additional runtime packages are needed.

Next Steps

Quickstart

Install dependencies, start the server, and make your first API call in under five minutes.

API Reference

Explore every endpoint, request body, and response schema for Users and Tasks.

Build docs developers (and LLMs) love