A simple URL shortener built with Flask, MySQL, and SQLAlchemy.
This project lets you shorten long URLs into short codes and redirect users back to the original links.
- Shorten long URLs into unique codes
- Redirect to original URLs when visiting short links
- Avoid duplicate entries (reuse code for the same long URL)
- Health-check endpoint
- Database migrations using Flask-Migrate
- Flask (Web framework)
- MySQL (Database)
- SQLAlchemy (ORM)
- Flask-Migrate (Database migrations)
- dotenv (Environment variable management)
url-shortener/
│── app.py # Main Flask application
│── config.py # Configuration file (DB credentials etc.)
│── requirements.txt # Python dependencies
│── templates/
└── index.html # Basic UI
│── migrations/ # Auto-generated by Flask-Migrate
└── README.mdgit clone https://github.com/G-coding/CodeAlpha_URLShortener.git
cd url-shortenerpython -m venv venv
source venv/bin/activate # Mac/Linux
venv\Scripts\activate # Windowspip install -r requirements.txtCreate a .env file in the project root:
DB_USER=root
DB_PASSWORD=Password@1234
DB_HOST=localhost
DB_NAME=url_shortenerUpdate config.py to use these environment variables.
1. Create MySQL Database
CREATE DATABASE url_shortener;
2. Initialize Migrations
flask db init
3. Generate Migration
flask db migrate -m "Initial migration"
4. Apply Migration
flask db upgradeOption 1: Flask Run
flask run
Option 2: Python Run
python app.py
By default, the app runs on:
👉 http://127.0.0.1:5000/- Shorten a URL
POST /api/shorten
{
"url": "https://www.amazon.in/s?k=wireless+headphones&crid=2TQHPFJ3N1G44&sprefix=wireless+headphones%2Caps%2C256&ref=nb_sb_noss_1"
}{
"short_url": "http://127.0.0.1:5000/BI6ZIS7",
"code": "BI6ZIS7"
}- Redirect
GET/
Redirects the user to the original long URL.
- Health Check
GET /health
{
"status": "ok"
}🧑💻 Example Usage
curl -X POST http://127.0.0.1:5000/api/shorten \
-H "Content-Type: application/json" \
-d '{"url":"https://www.wikipedia.org/"}'{
"short_url": "http://127.0.0.1:5000/aB3xYz1",
"code": "aB3xYz1"
}