A fully functional URL Shortener built with FastAPI and MongoDB.
This API converts long URLs into short, shareable tokens and automatically redirects users when they visit the short link.
| Feature | Description |
|---|---|
| 🧾 Shorten URLs | Converts long URLs into 10-character short tokens |
| 🔁 Redirect | Automatically redirects users to the original link |
| 🔐 Unique Tokens | Uses secure random generator from Python’s secrets |
| 💾 Database | Stores URL-token pairs in MongoDB |
| ⚡ Quick Docs | / route redirects directly to FastAPI Docs |
Project_25_URL_Shortener_API/
│
├── main.py
├── requirements.txt
└── .env
git clone https://github.com/yourusername/url-shortener-api.git
cd url-shortener-apipython -m venv venv
source venv/bin/activate # Linux/macOS
venv\Scripts\activate # Windowspip install -r requirements.txtCreate a .env file:
MONGO_URI=mongodb+srv://your_user:password@cluster-url/
uvicorn main:app --reloadVisit 👉 http://127.0.0.1:8000/docs
| Method | Route | Description |
|---|---|---|
GET |
/ |
Redirects to API Docs |
POST |
/short |
Shorten a URL |
GET |
/{token} |
Redirects to original URL |
POST /short
{
"url": "https://www.python.org/downloads/release/python-3110/"
}✅ Response:
{
"status": 200,
"message": "recorded",
"url": "http://localhost:8000/Zx9AB12kLm"
}Open your browser:
http://localhost:8000/Zx9AB12kLm
You’ll be redirected instantly to the original link.
┌───────────────┐
│ Long URL │
└──────┬────────┘
│
▼
[ FastAPI POST /short ]
│
Generates Random Token
│
Saves {token:url} in MongoDB
│
▼
Returns short link → /{token}
│
▼
[ GET /{token} → Redirects user ]
- Working with
secrets&stringmodules for random tokens - Using MongoDB CRUD with PyMongo
- Redirecting with
RedirectResponse - Input validation using Pydantic
- Safe error handling and try-catch patterns
fastapi==0.117.1
uvicorn==0.37.0
pymongo==4.15.1
python-dotenv==1.1.1
pydantic==2.11.9
- Add analytics (click count, timestamp, IP)
- Add expiration date for short links
- Add custom aliases (user-defined tokens)
- Create web frontend to generate short links
Developed by: Pinaka Course: CodeShiksha – Python Bhasha Mastery Year: © 2025