A modern, scalable, and secure URL shortener built with FastAPI, MongoDB, Redis, and Docker. This service allows you to shorten URLs with optional user authentication, custom aliases, usage analytics, and caching for optimal performance.
- β Shorten any valid URL
- π Optional user authentication (OAuth2/JWT)
- βοΈ Custom aliases for your short links
- β‘ Redis caching for fast redirects
- π³ Dockerized for easy deployment
- FastAPI β Web framework
- MongoDB β Database for storing URLs
- Redis β Caching layer for performance
- Pydantic β Data validation
- JWT / OAuth2 β Authentication
- Docker β Containerized app
fastapi-url-shortener/
β
βββ deploy/
β βββ app/ # Application source code
β β βββ controllers/ # Route handlers
β β βββ core/ # Configuration & DB setup
β β βββ models/ # Pydantic and MongoDB models
β β βββ routes/ # FastAPI routers
β β βββ schemas/ # Request/Response schemas
β β βββ services/ # Business logic
β β βββ utils/ # Utility functions
β β βββ __init__.py
β β βββ main.py # Entry point
β β
β βββ Dockerfile # Docker build instructions
β βββ docker-compose.yml # Multi-container setup
β βββ requirements.txt # Python dependencies
β
βββ env/ # Environment variables
git clone https://github.com/yourusername/fastapi-url-shortener.git
cd fastapi-url-shortenerCreate a .env file in the env/ directory and configure the following:
SECRET_KEY=your-secret-key
ALGORITHM=HS256
MONGO_URI=mongodb://mongo:27017
REDIS_URL=redis://redis:6379
REDIS_PASSWORD=your-redis-password
ACCESS_TOKEN_EXPIRE_MINUTES=30For Redis Cloud, use the provided URL with username and password. The REDIS_PASSWORD is required when using Redis Cloud as a service.
Navigate to the deploy/ directory and run:
cd deploy
docker-compose up --buildThe application will be available at: http://localhost:8000/docs
This project uses Docker Compose to run:
- FastAPI app on port 8000
- MongoDB on port 27017
- Redis on port 6379
You can inspect the full setup in deploy/docker-compose.yml.
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /v1/shorten | Shorten URL (unauthenticated) | β |
| POST | /v2/shorten | Shorten URL (authenticated) | β |
| GET | /{short_hash} | Redirect to original URL | β |
| POST | /api/auth/register | Register a new user | β |
| POST | /api/auth/login | Login and get access token | β |
The recommended way to run this application is using Docker, which takes care of all dependencies and services:
- Make sure Docker and Docker Compose are installed on your system
- Navigate to the deploy directory:
cd deploy- Build and start the containers:
docker-compose up --buildThis will start the FastAPI application, MongoDB, and Redis all configured to work together.
This project is licensed under the MIT License.
Charles
Built with β€οΈ using FastAPI