Skip to content

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

URL_ShortnerPY

A full-stack URL shortener built with Python, FastAPI, PostgreSQL, HTML, CSS, and JavaScript.

The application accepts a long URL, generates a unique Base62-based short code, stores the mapping in PostgreSQL, and redirects users to the original URL through the generated short link.

🚀 Live Application

Frontend: https://urlshortnerfront.vercel.app/

Backend API: https://url-shortnerpy.onrender.com/

API Documentation: https://url-shortnerpy.onrender.com/docs


📌 Features

  • Accepts and validates URLs before shortening
  • Generates unique short codes using Base62 encoding
  • Stores URLs and short codes in PostgreSQL
  • Returns a shortened URL to the user
  • Redirects users from the short URL to the original URL
  • Returns an appropriate error when a short code does not exist
  • Separates database operations from URL-shortening logic
  • REST API built using FastAPI
  • Frontend deployed separately from the backend
  • PostgreSQL database hosted on Render
  • Backend hosted on Render
  • Frontend hosted on Vercel

🛠️ Tech Stack

Backend

  • Python
  • FastAPI
  • Uvicorn
  • Pydantic
  • psycopg2

Database

  • PostgreSQL

Frontend

  • HTML
  • CSS
  • JavaScript

Deployment

  • Vercel — Frontend
  • Render — FastAPI Backend
  • Render PostgreSQL — Database

🏗️ Architecture

                    ┌──────────────────────┐
                    │       Vercel         │
                    │   HTML/CSS/JS        │
                    │      Frontend        │
                    └──────────┬───────────┘
                               │
                         HTTP Requests
                               │
                               ▼
                    ┌──────────────────────┐
                    │       Render         │
                    │      FastAPI         │
                    │       Backend        │
                    └──────────┬───────────┘
                               │
                           psycopg2
                               │
                               ▼
                    ┌──────────────────────┐
                    │       Render         │
                    │      PostgreSQL      │
                    │    url_handler       │
                    └──────────────────────┘

🔄 Application Flow

Creating a Short URL

User enters URL
       ↓
Frontend sends POST /shorten
       ↓
FastAPI receives the URL
       ↓
Pydantic validates the URL
       ↓
URL is stored in PostgreSQL
       ↓
Database generates a unique ID
       ↓
ID is converted to Base62
       ↓
Short code is generated
       ↓
Short code is stored in PostgreSQL
       ↓
Short URL is returned to the frontend

Redirecting to the Original URL

User opens short URL
       ↓
GET /{short_code}
       ↓
FastAPI searches PostgreSQL
       ↓
Short code found?
     /       \
   Yes        No
    ↓          ↓
Redirect     404 Error
to original
URL

🔌 API Endpoints

POST /shorten

Creates a shortened URL.

Request:

{
    "homepage": "https://www.example.com"
}

Response:

{
    "New_URL": "https://url-shortnerpy.onrender.com/abc123"
}

GET /{short_code}

Redirects the user to the original URL associated with the given short code.

Example:

GET /abc123

If abc123 exists, the user is redirected to the original URL.

If the short code does not exist, the API returns an appropriate error response.


🗄️ Database Schema

The application uses a single PostgreSQL table named url_handler.

Column Type Description
id BIGINT Primary key and source for short-code generation
user_URL VARCHAR(255) Original URL submitted by the user
short_Code VARCHAR(255) Generated Base62 short code
created_at TIMESTAMPTZ Timestamp when the URL was created

SQL Schema

CREATE TABLE url_handler (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY
        (START WITH 10000000) PRIMARY KEY,
    user_URL VARCHAR(255) NOT NULL,
    short_Code VARCHAR(255),
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

🔢 URL Shortening Logic

The application uses Base62 encoding to convert the database-generated ID into a shorter string.

The Base62 character set is:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

For example:

Database ID
    ↓
Base62 Encoding
    ↓
Short Code
    ↓
abc123

The generated short code is then stored alongside the original URL in PostgreSQL.


📁 Project Structure

URL_ShortnerPY/
│
├── Backend/
│   ├── Database/
│   │   └── Database.py
│   │
│   ├── app.py
│   ├── shorten_url.py
│   └── requirements.txt
│
├── Frontend/
│   ├── index.html
│   ├── script.js
│   └── style.css
│
├── README.md
├── Shortening_logic.md
└── workflow.md

Backend Files

app.py

Contains the FastAPI application and API endpoints.

Database/Database.py

Handles PostgreSQL connectivity and database operations such as:

  • Inserting original URLs
  • Updating short codes
  • Searching for short codes
  • Retrieving stored URLs

shorten_url.py

Contains the URL-shortening logic, including Base62 conversion.

requirements.txt

Contains the Python dependencies required by the backend.

Frontend Files

index.html

Contains the structure of the URL shortener interface.

style.css

Contains the styling for the frontend.

script.js

Handles user interaction and communication with the FastAPI backend using fetch().


🔐 Environment Variables

Database credentials are not hardcoded into the application.

The backend uses:

DATABASE_URL

For local development, the variable can be stored in a .env file.

For production, the variable is configured through Render's environment variables.

Example:

DATABASE_URL=<your-postgresql-connection-string>

The .env file should never be committed to GitHub.


💻 Running Locally

1. Clone the repository

git clone <repository-url>
cd URL_ShortnerPY

2. Create and activate a virtual environment

python -m venv .venv

Linux/macOS:

source .venv/bin/activate

Windows:

.venv\Scripts\activate

3. Install dependencies

pip install -r Backend/requirements.txt

4. Configure environment variables

Create a .env file:

DATABASE_URL=postgresql://username:password@localhost:5432/database

5. Start the FastAPI server

From the project root:

uvicorn Backend.app:app --reload

The API will be available at:

http://127.0.0.1:8000

Swagger documentation:

http://127.0.0.1:8000/docs

☁️ Deployment

The project is deployed using separate services:

Frontend → Vercel
Backend  → Render
Database → Render PostgreSQL

Frontend

The HTML, CSS, and JavaScript frontend is deployed on Vercel.

Backend

The FastAPI application is deployed as a Render Web Service.

Database

The PostgreSQL database is hosted using Render PostgreSQL.

The backend connects to the production database using the DATABASE_URL environment variable.


📋 Functional Requirements

Requirement Status
Accept URL input from the user ✅
Validate the URL ✅
Generate a unique shortened URL ✅
Store the URL in a database ✅
Return the shortened URL ✅
Redirect to the original URL ✅
Handle invalid/non-existent short codes ✅
Delete shortened URLs 🚧

📋 Non-Functional Requirements

  • Generated short codes should not conflict with existing codes.
  • Appropriate HTTP status codes should be returned.
  • URLs must be validated before processing.
  • Database operations are separated from URL-shortening logic.
  • Database credentials are stored using environment variables.
  • Backend and frontend are deployed independently.

🎯 Future Improvements

Some features that can be added in future versions:

  • Delete shortened URLs
  • Custom short codes
  • URL expiration
  • Click/visit analytics
  • Rate limiting
  • User authentication
  • User-specific URL management
  • Improved error handling
  • Automated database migrations
  • Unit and integration tests

📚 Project Documentation

Additional project documentation:

  • Shortening_logic.md — Explanation of the Base62 shortening algorithm
  • workflow.md — Development and application workflow

👨‍💻 Author

Amish Mathur

Built as a backend-focused project to understand REST APIs, FastAPI, PostgreSQL, database interaction, URL shortening algorithms, and full-stack deployment.

About

Full-stack URL shortener built with FastAPI, PostgreSQL, and JavaScript. Uses Base62 encoding to generate unique short links with high-speed redirects.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages