A robust, scalable RESTful API for managing users and blog posts, built with FastAPI and MongoDB. This project demonstrates modern backend development practices, including asynchronous operations, secure authentication, and serverless-optimized deployment.
- User Management: Secure user registration and retrieval with password hashing
- Blog Management: Full CRUD operations for blog posts with user association
- JWT Authentication: Token-based authentication for protected endpoints
- MongoDB Integration: NoSQL database with Beanie ODM for efficient data handling
- Asynchronous Operations: Fully async endpoints for high performance
- Modular Architecture: Clean separation of concerns with routers, repositories, and schemas
- Serverless Optimized: Configured for Vercel with connection pooling and error handling
- Health Monitoring: Built-in health checks and database status monitoring
- Interactive Documentation: Auto-generated API docs with Swagger UI
- Production Ready: Comprehensive logging, error handling, and environment configuration
- Framework: FastAPI
- Database: MongoDB with Motor (async driver) and Beanie ODM
- Authentication: JWT tokens with python-jose
- Password Hashing: bcrypt with passlib
- Deployment: Vercel (serverless) with Railway (database hosting)
- Validation: Pydantic schemas
├── app/
│ ├── main.py # FastAPI application entry point
│ ├── requirements.txt # Python dependencies
│ ├── blog/
│ │ ├── models.py # Beanie document models
│ │ ├── schemas.py # Pydantic request/response schemas
│ │ ├── database.py # MongoDB connection and initialization
│ │ ├── hashing.py # Password hashing utilities
│ │ ├── JWTtoken.py # JWT token creation/verification
│ │ ├── oauth2.py # OAuth2 authentication dependency
│ │ ├── routers/ # API route handlers
│ │ │ ├── authentication.py
│ │ │ ├── blog.py
│ │ │ └── user.py
│ │ └── repository/ # Business logic layer
│ │ ├── blog.py
│ │ └── user.py
├── vercel.json # Vercel deployment configuration
└── README.md
- Python 3.8+
- MongoDB instance (local or cloud)
- Vercel account (for deployment)
-
Clone the repository:
git clone https://github.com/BROOKS69/Blog-FastAPI cd fastapi-blog-api -
Create virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r app/requirements.txt
-
Set environment variables:
export MONGODB_URL="mongodb://localhost:27017/blogdb" export SECRET_KEY="your-secret-key-here"
-
Run the application:
uvicorn app.main:app --reload
-
Access the API:
- API: http://localhost:8000
- Documentation: http://localhost:8000/docs
For local development, ensure MongoDB is running. For production, use Railway's free MongoDB service.
Railway provides free hosting for both your app and MongoDB database.
- Go to railway.app and sign up
- Create a new project
- In your project dashboard, click "Add Service"
- Search for "MongoDB" and add it
- Railway will provision a free MongoDB instance
- Copy the
DATABASE_URLfrom the MongoDB service variables (it looks likemongodb://mongo:password@containers-us-west-1.railway.app:1234/railway)
- Click "Add Service" again
- Choose "GitHub" to connect your repository
- Select your FastAPI project repository
- Railway will detect it's a Python app
- In your app service, go to "Variables"
- Add:
MONGODB_URL: Paste the MongoDB connection string from step 2SECRET_KEY: Generate a secure random string (e.g.,openssl rand -hex 32)
- Railway will automatically build and deploy your app
- Check the deployment logs for any errors
- Once deployed, get the app URL from the service dashboard
- Use the Railway app URL + your endpoints (e.g.,
https://blog-fast-api.railway.app/docsfor docs) - Test user creation, login, and blog operations
If you prefer Vercel's serverless functions:
- Push your code to GitHub
- Go to vercel.com and sign up
- Click "New Project" and import from GitHub
- Vercel will detect
vercel.jsonand configure automatically
- In project settings > Environment Variables:
MONGODB_URL: Your Railway MongoDB connection stringSECRET_KEY: Secure random string
- Vercel will build and deploy
- Test using the Vercel URL
To test locally with your Railway database:
- Copy the
DATABASE_URLfrom Railway - Set environment variable:
export MONGODB_URL="your-railway-connection-string" - Run locally:
uvicorn app.main:app --reload - Test endpoints as usual
POST /register- Create new userPOST /login- User login (returns JWT token)
GET /user/{id}- Get user by ID
GET /blog- Get all blogs (authenticated)POST /blog- Create new blog (authenticated)GET /blog/{id}- Get blog by IDPUT /blog/{id}- Update blog (authenticated)DELETE /blog/{id}- Delete blog (authenticated)
MONGODB_URL: MongoDB connection stringSECRET_KEY: JWT signing key (generate a secure random string)
The vercel.json file configures the build and routing for serverless deployment.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with FastAPI
- Database ODM: Beanie
- MongoDB Driver: Motor
- Authentication: python-jose
- Deployment: Vercel & Railway
This project has been optimized for serverless deployment with several key improvements:
-
Database Connection: Fixed MongoDB connection issues in serverless environments
- Added connection pooling with optimized timeouts
- Proper error handling for connection failures
- Environment-specific MongoDB URL configuration
-
Application Lifecycle: Improved startup/shutdown handling
- Added comprehensive lifespan management
- Database initialization with health checks
- Graceful error handling during startup
-
Error Handling: Enhanced error handling and logging
- Detailed error messages for debugging
- Health check endpoint (
/health) - Proper HTTP status codes for different error types
-
Vercel Configuration: Optimized for serverless deployment
- Updated
vercel.jsonwith proper settings - Memory and timeout configurations
- Regional deployment optimization
- Updated
Before deploying to Vercel:
-
Set Environment Variables in Vercel Dashboard:
MONGODB_URL: Your MongoDB connection stringSECRET_KEY: Secure JWT signing keyENVIRONMENT: Set to "production"
-
Test Locally First:
export MONGODB_URL="your-mongodb-connection-string" export SECRET_KEY="your-secret-key" uvicorn app.main:app --reload
-
Check Health Endpoint:
- Visit
/healthto verify database connectivity - Check
/docsfor API documentation
- Visit
Common Issues:
-
Database Connection Failed:
- Verify
MONGODB_URLenvironment variable is set correctly - Check MongoDB server is accessible from serverless environment
- Ensure MongoDB allows connections from 0.0.0.0/0 (Vercel's IP range)
- Verify
-
Application Won't Start:
- Check Vercel deployment logs for detailed error messages
- Verify all dependencies are in
requirements.txt - Ensure Python version compatibility (3.8+)
-
Timeout Errors:
- Database operations may timeout in serverless
- Consider implementing caching for frequently accessed data
- Optimize database queries for performance
-
Cold Start Issues:
- Serverless functions have cold start delays
- The first request may take longer due to database initialization
- Use connection pooling to minimize connection overhead
Debugging Tips:
- Check Vercel function logs in the dashboard
- Use the
/healthendpoint to test database connectivity - Monitor MongoDB connection pool usage
- Enable detailed logging by setting
DEBUG=Truein environment variables
For questions or issues, please open a GitHub issue or contact the maintainers.