A lightweight and efficient URL shortening service implemented in Python using Flask. This service provides URL shortening, redirection, and analytics capabilities with thread-safe operations and in-memory storage.
- Generate short URLs with 6-character alphanumeric codes
- Redirect to original URLs with click tracking
- View analytics (click counts and creation timestamps)
- Thread-safe operations for concurrent access
- Comprehensive test coverage
- Python 3.8+
- Flask 2.3.2
# Clone the repository
git clone https://github.com/suryanshgargbpgc/url_shortener.git
cd url_shortener
# Install dependencies
pip install -r requirements.txt
# Start the application
python -m flask --app app.main run
# Run tests
pytestThe API will be available at http://localhost:5000
url_shortener/
├── app/
│ ├── __init__.py
│ ├── main.py # API endpoints and Flask application
│ ├── models.py # Data storage and thread-safe operations
│ └── utils.py # URL validation and code generation
├── tests/
│ └── test_basic.py # Comprehensive test suite
└── requirements.txt # Project dependencies
POST /api/shorten
Content-Type: application/json
{
"url": "https://www.example.com/very/long/url"
}Response:
{
"short_code": "abc123",
"short_url": "http://localhost:5000/abc123"
}GET /<short_code>Redirects to the original URL or returns 404 if not found.
GET /api/stats/<short_code>Response:
{
"url": "https://www.example.com/very/long/url",
"clicks": 5,
"created_at": "2025-07-24T11:55:45"
}
## Technical Implementation
### Key Features
- Thread-safe operations using `threading.Lock`
- URL validation using `urllib.parse`
- In-memory storage with Python dictionary
- 6-character alphanumeric short codes
- Comprehensive error handling
- Full test coverage
### Example Usage with curl
```bash
# Create a short URL
curl -X POST http://localhost:5000/api/shorten \
-H "Content-Type: application/json" \
-d '{"url": "https://www.google.com"}'
# Visit the URL (use -L to follow redirects)
curl -L http://localhost:5000/<short_code>
# Get statistics
curl http://localhost:5000/api/stats/<short_code>The project includes comprehensive tests covering:
- URL shortening functionality
- URL validation
- Redirection behavior
- Analytics tracking
- Concurrent access handling
Run tests using:
pytest -v- Invalid URLs return 400 Bad Request
- Non-existent short codes return 404 Not Found
- All errors return appropriate HTTP status codes and messages
- In-Memory Storage: Used Python dictionary for fast access and simplicity
- Thread Safety: Implemented using threading.Lock for concurrent access
- URL Validation: Robust validation using urllib.parse
- Short Code Generation: Random 6-character alphanumeric codes
- Error Handling: Comprehensive HTTP status codes and messages
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.