This is a clean, modular URL Shortener API built using:
- β FastAPI for the web API
- β PostgreSQL as the main database (with SQLite fallback if Postgres is unavailable)
- β Base62 encoding for short, unique, and human-friendly short codes
It has 2 main endpoints:
- Input: A long URL (e.g.,
https://www.google.com) - Output: A short URL (e.g.,
http://localhost:8000/bM9)
β If the same URL is sent again, it returns the existing short URL (no duplication).
- Input: A short code from the URL (like
bM9) - Output: Redirects to the original long URL
Short code generation is deterministic and unique:
- When a new URL is added, it's assigned a unique auto-incrementing ID in the database.
- This ID is converted into a Base62 string (digits + AβZ + aβz).
- π Codes are always unique
- β No random collisions
- π Codes are shorter over time (first few are just 1β2 characters like
1,a,B,z, etc.)
β Even if a user sends the same URL again β it reuses the original short code.
url_shortener/
βββ app/
β βββ main.py # FastAPI app entry point
β βββ database.py # Sets up DB connection (Postgres or fallback to SQLite)
β βββ models.py # DB table definition using SQLAlchemy
β βββ schemas.py # Request/Response format validation (Pydantic)
β βββ utils.py # Encodes integer ID to Base62
β βββ routers/
β βββ url.py # Main routing logic: shortening and redirecting
βββ requirements.txt # All needed packages
If DATABASE_URL is not set (e.g. in .env or environment variables), it automatically uses:
sqlite:///./url_shortener.db
This helps:
- β Run the project locally without setting up Postgres
- π Still allows switching to Postgres in production (just set the
DATABASE_URL)
-
Clone the repo or create files as shown
-
Create a virtual environment (optional but recommended)
python -m venv venv
source venv/bin/activate # or `venv\Scripts\activate` on Windows- Install dependencies
pip install -r requirements.txtIf
requirements.txtdoesn't exist yet, use:
pip install fastapi uvicorn sqlalchemy psycopg2-binary- Run the app
uvicorn app.main:app --reloadPOST http://localhost:8000/shorten
Content-Type: application/json
{
"original_url": "https://openai.com"
}Response:
{
"short_url": "http://localhost:8000/bM9"
}Open in browser:
http://localhost:8000/bM9
It redirects you to:
https://openai.com