A β¨ simple, elegant URL shortener application built with FastAPI, following Clean Architecture and Domain-Driven Design (DDD) principles. This project demonstrates how to build a maintainable and scalable architecture while keeping things lightweight and developer-friendly.
- π Features
- ποΈ Architecture
- π§ Domain-Driven Design
- π Project Structure
- βοΈ Installation
- π API Endpoints
- π€ Contributing
- π License
- π Shorten long URLs for easier sharing.
- π₯ Retrieve original URLs from short codes.
- π§± Clean and modular architecture using DDD.
- β‘ Built on FastAPI for speed and simplicity.
- β Unit-tested for reliability.
- π§© Domain Events & Value Objects support.
The app follows Clean Architecture, dividing responsibilities across layers for separation of concerns:
- π£οΈ Delivery Layer: Handles HTTP requests with FastAPI.
- π§ Domain Layer: Business logic, entities, value objects, and domain events.
- βοΈ Application Layer: Use cases and orchestrators.
- ποΈ Infrastructure Layer: DB access and external APIs.
UrlAggregate: Manages URL lifecycle.- πΉ Root:
Url - πΉ Value Objects:
ShortCode,OriginalUrl
- πΉ Root:
ShortCode: Shortened URL stringOriginalUrl: Validated original URL
UrlShortenedEvent: Fired when a URL is shortened.UrlAccessedEvent: Triggered when a URL is accessed.
- URL Management (current context).
src/
βββ domain/ # Core business logic
β βββ exceptions/
β βββ value_objects.py
β βββ url.py
β βββ url_repository.py
β βββ events.py
βββ application/ # Use cases & services
β βββ create_short_url.py
β βββ get_original_url.py
β βββ get_url_stats.py
β βββ get_all_urls.py
βββ infrastructure/ # DB and external service handling
β βββ dto/
β βββ storage/
β βββ shortener/
β βββ events/
βββ delivery/ # API layer with FastAPI
β βββ api/
β βββ dependencies.py
β βββ routers.py
βββ config.py # Centralized configuration
βββ main.py # Main entry point
- Clone the repository:
git clone https://github.com/fabianfalon/url-shortener-clean-architecture.git
cd url-shortener-clean-architecture- Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate- Install dependencies:
pip install -r requirements.txt
# or for dev and test support
pip install -r requirements-tests.txt- Run the app:
uvicorn app.main:app --reloaddocker-compose build
docker-compose up| Method | Endpoint | Description |
|---|---|---|
| POST | /shorten |
Shorten a long URL |
| GET | /urls |
List all shortened URLs |
| GET | /{shortened_id} |
Retrieve the original URL |
| GET | /{short_code}/stats |
Get URL statistics |
POST /shorten
Content-Type: application/json
{
"url": "https://example.com/some/long/url"
}GET /urls
Content-Type: application/json
{
"urls": [
{
"id": 1,
"short_url": "abc123"
}
]
}GET /abc123
Content-Type: application/jsonContributions are welcome! π Feel free to fork the repo and submit a pull request with improvements or bug fixes.
This project is licensed under the MIT License. See the LICENSE file for more details.