AWS Builder Center

Building a FastAPI Backend with MongoDB: A Practical Guide

Learn how to build a REST API using FastAPI and MongoDB, configure authentication and CORS, organize API routes, and run the backend locally for a modern web application.

Building a FastAPI Backend with MongoDB: A Practical Guide

Modern web applications need a reliable backend to handle authentication, data storage, business logic, and communication between the frontend and database. In this article, we will explore how to build a backend using FastAPI and MongoDB.
The same architecture can be used for projects such as learning platforms, gaming applications, dashboards, and AI-powered web applications.

1. What is FastAPI?

FastAPI  is a modern Python framework for building APIs.
It provides:
  • High performance
  • Automatic API documentation
  • Type validation using Python type hints
  • Easy request and response handling
  • Support for asynchronous programming
  • Simple project organization
FastAPI automatically provides interactive API documentation through Swagger UI.
After starting the application, developers can usually access:
1
http://127.0.0.1:8000/docs
This makes it easy to test API endpoints without creating a separate API testing interface.

2. Why MongoDB?

MongoDB is a NoSQL database that stores information in document-oriented structures.
Instead of storing data in traditional rows and columns, MongoDB stores documents similar to JSON.
For example:
1
2
3
4
5
{
"username": "roshan",
"email": "roshan@example.com",
"score": 120
}
This approach is useful when an application needs flexible data structures.
MongoDB can be used for storing:
  • User accounts
  • Scores
  • Game data
  • Leaderboards
  • User activity
  • Application settings

3. Basic Project Structure

A FastAPI project can be organized into separate modules so that each part of the application has a clear responsibility.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
backend/
│
├── app/
│ ├── main.py
│ ├── config.py
│ ├── database.py
│ │
│ └── routers/
│ ├── auth.py
│ ├── users.py
│ ├── challenges.py
│ ├── leaderboard.py
│ └── translate.py
│
├── requirements.txt
├── .env
└── README.md
This structure keeps the project maintainable as the application grows.

4. Connecting FastAPI to MongoDB

The database connection can be configured using environment variables.
For example:
1
2
MONGODB_URI=mongodb://localhost:27017
MONGODB_DB_NAME=mydatabase
For a production application, a MongoDB Atlas connection string can be used instead of a local MongoDB server.
Keeping database credentials in environment variables is preferable to placing them directly inside source code.

5. Application Configuration

FastAPI applications often have settings for:
  • Database connection
  • JWT authentication
  • CORS
  • Token expiration
  • Application configuration
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
mongodb_uri: str
mongodb_db_name: str

jwt_algorithm: str = "HS256"
access_token_expire_minutes: int = 10080

class Config:
env_file = ".env"


settings = Settings()
This allows configuration to be changed without modifying the application source code.

6. Creating the FastAPI Application

The main application can be created using FastAPI.
1
2
3
4
5
6
7
8
9
10
11
from fastapi import FastAPI

app = FastAPI(
title="My Application API",
version="1.0.0"
)


@app.get("/api/health")
async def health():
return {"status": "ok"}
The /api/health endpoint can be used to check whether the backend is running correctly.
When the server is started, opening:
1
http://127.0.0.1:8000/api/health
should return:
1
2
3
{
"status": "ok"
}

7. Organizing API Routers

As an application grows, putting every endpoint inside main.py becomes difficult to maintain.
FastAPI allows endpoints to be separated into routers.
For example:
1
2
3
4
5
6
7
8
9
10
11
from fastapi import APIRouter

router = APIRouter(
prefix="/api/users",
tags=["Users"]
)


@router.get("/")
async def get_users():
return {"message": "User list"}
The router can then be included in the main application:
1
2
3
from app.routers import users

app.include_router(users.router)
This creates a cleaner architecture.

8. Authentication

Most applications require authentication so that users can securely access their accounts.
A common approach is:
1
2
3
4
5
6
7
8
9
10
11
12
13
User
↓
Register
↓
Login
↓
Verify credentials
↓
Generate JWT
↓
Client stores token
↓
Token sent with protected requests
JWT, or JSON Web Token, can be used to authenticate API requests.
A simplified request may contain:
1
Authorization: Bearer <token>
The backend validates the token before allowing access to protected endpoints.

9. CORS Configuration

When a frontend and backend run on different origins, browsers enforce Cross-Origin Resource Sharing (CORS) rules.
For example:
1
2
Frontend → http://localhost:5500
Backend → http://localhost:8000
The backend needs to explicitly allow the frontend origin.
FastAPI provides CORSMiddleware for this:
1
2
3
4
5
6
7
8
9
10
11
12
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5500",
"http://127.0.0.1:5500"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
One common development problem occurs when the browser uses a different origin than the one configured in allow_origins.
For example, these are different origins:
1
2
3
http://localhost:5500
http://127.0.0.1:5500
http://[::]:5500
Therefore, the actual browser origin must be considered when troubleshooting CORS errors.

10. Database Operations

The backend can perform common database operations such as:

Create

Insert a new document:
1
2
3
4
await users_collection.insert_one({
"username": username,
"email": email
})

Read

Retrieve a document:
1
2
3
user = await users_collection.find_one({
"email": email
})

Update

Update existing information:
1
2
3
4
await users_collection.update_one(
{"email": email},
{"$set": {"score": 100}}
)

Delete

Remove a document:
1
2
3
await users_collection.delete_one({
"email": email
})
These operations allow the API to communicate with MongoDB and provide persistent application data.

11. Example Request Flow

Consider a user logging into a web application.
The complete process can look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Browser
│
│ POST /api/auth/login
▼
FastAPI
│
│ Validate request
▼
Authentication Router
│
│ Check user
▼
MongoDB
│
│ User found
▼
FastAPI
│
│ Generate JWT
▼
Browser
The browser can then use the JWT when accessing protected API endpoints.

12. Running the Application

First create a virtual environment:
1
python -m venv venv
Activate it.
On macOS/Linux:
1
source venv/bin/activate
Install dependencies:
1
pip install -r requirements.txt
Then start FastAPI:
1
uvicorn app.main:app --reload --port 8000
The backend will be available at:
1
http://127.0.0.1:8000
Swagger documentation can be accessed at:
1
http://127.0.0.1:8000/docs

13. Testing the API

Swagger UI makes API testing straightforward.
A typical workflow is:
1
2
3
4
5
6
7
8
9
10
11
12
13
Start FastAPI
↓
Open /docs
↓
Select an endpoint
↓
Click "Try it out"
↓
Enter request data
↓
Execute
↓
Inspect response
This is particularly useful during development because API endpoints can be tested independently of the frontend.

14. Production Considerations

Before deploying a FastAPI application, several areas should be reviewed.

Environment Variables

Do not hard-code:
  • Database passwords
  • JWT secrets
  • API keys
  • Other credentials
Use environment variables or a suitable secret-management system.

CORS

Only allow the frontend origins that actually need access in production.

Authentication

Use a strong secret key and appropriate token expiration settings.

Database

For production applications, configure MongoDB with appropriate authentication, network access controls, backups, and monitoring.

Logging

Application logs should provide enough information for troubleshooting without exposing sensitive information.

15. Conclusion

FastAPI and MongoDB provide a flexible foundation for building modern web application backends.
A typical architecture separates responsibilities into:
1
2
3
4
5
6
7
8
9
Frontend
↓
FastAPI API
↓
Routers
↓
Authentication / Business Logic
↓
MongoDB
FastAPI handles HTTP requests and API documentation, routers organize application functionality, authentication protects user resources, and MongoDB provides persistent storage.
By keeping configuration, database operations, authentication, and API routes modular, the backend becomes easier to test, maintain, and extend.
This architecture can serve as a starting point for applications ranging from simple CRUD systems to larger platforms containing authentication, leaderboards, user profiles, and other interactive features.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article