In this final project, you will build a fully functional User Management REST API from scratch using pure Python and MongoDB.
The project consolidates all concepts learned in previous modules: Python foundations, MongoDB basics, Python–MongoDB integration, and building REST APIs.
You will also implement JWT-based authentication, profile CRUD operations, filtered searches, aggregation endpoints, and API documentation.
✅ Project Overview
- REST API built using Python’s
http.serverandBaseHTTPRequestHandler. - MongoDB as the database (local or Atlas).
- User authentication using JWT (JSON Web Tokens).
- CRUD operations for user profiles.
- List and search users with filters (age, role, status, etc.).
- Aggregation endpoints (e.g., count users by role).
- Manual API documentation in Markdown or OpenAPI format.
✅ User Signup/Login with JWT Authentication
import jwt
import datetime
SECRET_KEY = "your_secret_key"
# Generate token
def generate_token(user_id):
payload = {
"user_id": str(user_id),
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
return token
# Verify token
def verify_token(token):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
return payload["user_id"]
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
Notes: Use JWT tokens for user authentication in protected endpoints. Tokens should be sent in the Authorization: Bearer <token> header.
✅ Profile CRUD Operations
# Example: Create user profile
def create_user(data):
result = users_collection.insert_one(data)
return str(result.inserted_id)
# Read profile
def get_user(user_id):
return users_collection.find_one({"_id": ObjectId(user_id)})
# Update profile
def update_user(user_id, data):
users_collection.update_one({"_id": ObjectId(user_id)}, {"$set": data})
# Delete profile
def delete_user(user_id):
users_collection.delete_one({"_id": ObjectId(user_id)})
✅ List/Search Users with Filters
# Filter users by age or role
def search_users(filters):
query = {}
if "age_gt" in filters:
query["age"] = {"$gt": filters["age_gt"]}
if "role" in filters:
query["role"] = filters["role"]
return list(users_collection.find(query))
✅ Aggregation Endpoint
# Count users by role
def count_users_by_role():
pipeline = [
{"$group": {"_id": "$role", "count": {"$sum": 1}}}
]
return list(users_collection.aggregate(pipeline))
✅ API Documentation (Markdown / OpenAPI)
Document your API manually using Markdown or OpenAPI format. Include:
- Endpoint URLs and HTTP methods
- Request headers and body format
- Response format
- Authentication requirements
- Sample requests and responses
✅ Best Practices for Final Project
- Organize code into folders:
handlers/,models/,utils/. - Handle exceptions and return proper HTTP status codes.
- Secure JWT secret keys using environment variables.
- Validate user inputs to prevent invalid data or injections.
- Use proper logging for debugging and monitoring.
✅ Exercises / Deliverables
- Build all API endpoints for user management.
- Implement JWT signup/login and protect profile routes.
- Enable filtered listing of users by age, role, or status.
- Create aggregation endpoints for statistics like user count by role.
- Prepare API documentation in Markdown or OpenAPI spec.
- Test the API using Postman or similar tools.
Congratulations! Completing this final project demonstrates your ability to build a production-ready REST API using pure Python and MongoDB, including authentication, CRUD operations, filtering, aggregation, and documentation.
You are now fully equipped to develop backend systems with Python and MongoDB without relying on external frameworks.
