This is a self-hosted, scalable URL shortening service built with FastAPI (Python), PostgreSQL, and Docker. It uses Base62 encoding to generate short, unique, and compact link codes.
- RESTful API: Dedicated endpoints for creating short links (
/api/shorten) and handling redirection (/{short_code}). - Scalable Core Logic: Uses an auto-incrementing PostgreSQL ID and mathematically converts it to a short, collision-free Base62 code.
- Containerised: Managed entirely via Docker Compose for easy setup, isolation, and portability.
- Basic Analytics: Tracks click count for every shortened URL.
- Fast Redirection: Uses an HTTP 302 (Temporary) redirect for trackable link clicks.
- Data Persistence: The PostgreSQL database utilizes a named Docker Volume (
postgres_data) defined indocker-compose.yml. This volume ensures that all your created URLs and click data remain safe and are not lost, even if the database container is stopped, removed, or restarted.
| Component | Role | Notes |
|---|---|---|
| Backend Framework | FastAPI (Python) | High-performance async web framework. |
| Database | PostgreSQL | Robust relational database for data persistence. |
| Short Code Logic | Base62 Encoding | Generates short, alphanumeric codes from unique IDs. |
| Containerization | Docker / Docker Compose | Manages the multi-service environment (App + DB). |
| ORM | SQLAlchemy | Python toolkit for database modeling. |
- Docker Desktop (Installed and running on macOS or windows)
- VS Code (Recommended IDE)
-
Launch the Services: From the root
url-shortenerdirectory, run the following command to build the application image and start both the PostgreSQL database and the FastAPI app:docker compose up -d --build
(The
--buildflag ensures your latest code and dependencies are always used.) -
Verify Startup: Check the logs for the application container (
app) to confirm it started successfully:docker compose logs -f app
The server is ready when you see the line:
INFO: Application startup complete. 🚀
The FastAPI application is available on your local machine at http://localhost:8000.
Access the interactive API documentation (Swagger UI):
http://localhost:8000/docs
Use the /api/shorten endpoint to submit a long URL.
Example (using cURL):
curl -X 'POST' \
'http://localhost:8000/api/shorten?long_url=https%3A%2F%2Fwww.example.com%2Fmy-very-long-article-slug' \
-H 'accept: application/json'
Successful Response: The short_code will be a unique Base62 string (e.g., "k2mK").
JSON
{
"short_code": "k2mK",
"original_url": "...",
"status": "created"
}Access the short code directly in your browser to trigger the 302 redirect.
URL: http://localhost:8000/{short_code}
Example: Navigate to http://localhost:8000/k2mK
Use the following commands when you are done working:
Stop Services
Stops the containers but preserves the PostgreSQL data volume:
docker compose down
Stops the containers and permanently deletes the database data volume (--volumes):
docker compose down --volumes