A simple URL shortening service built with FastAPI, featuring short code redirects, access logging, and admin access with environment variable authentication.
- Shorten long URLs to short codes
- Redirect short codes to original URLs
- Track visit counts and access logs
- Protected admin endpoint to view recent access logs
- Python 3.8+
- FastAPI
- SQLAlchemy
- SQLite/PostgreSQL
- Uvicorn (ASGI server)
- Python 3.8 or higher
pippackage manager- Database setup (SQLite by default, can use PostgreSQL or others)
git clone https://github.com/yourusername/your-repo.git
cd your-repo
pip install -r requirements.txtCreate a .env file in the project root or set environment variables directly:
SECRET_KEY=your-secret-key
Make sure to replace values with your actual secret key and database URL.
uvicorn main:app --reloadOpen your browser and visit:
- API docs: http://127.0.0.1:8000/docs
- Alternative docs: http://127.0.0.1:8000/redoc
for documentation on the API and its endpoints
POST /shorten- Shorten a long URLGET /{code}- Redirect to original URL for a given short codeGET /admin- Admin endpoint to view access logs (requirespasswrdquery param matchingSECRET_KEY)GET /show- Shows all the urls and shortcode present in the database(requiresshowquery param matchingall)
Run tests using pytest:
pytestSample test cases are provided in test_main.py file which can be run using
pytest test_main.py
Make sure environment variables like SECRET_KEY are set before running tests.
You can use a .env file or set them in your terminal session.
- Push your code to a GitHub repository.
- Go to https://render.com and create a new Web Service.
- Connect your GitHub repository.
- Set the following environment variables in the Render dashboard:
SECRET_KEY– your secret key for admin access - Choose:
- Build Command:
pip install -r requirements.txt - Start Command:
uvicorn main:app --host 0.0.0.0 --port 10000
- Build Command:
- Deploy the service and Render will handle the rest.
Your FastAPI app will be live at the URL provided by Render.
You can try the deployed URL shortener app here:
Url Shortener by aby-jo