Skip to content

Shorten a link

Shorten URL

Path: /api/v1/shorten
Method: POST

The shorten URL endpoint allows users to convert long, unwieldy URLs into compact, shareable short codes. This is the core functionality of the URL shortener API, enabling easier sharing and tracking.

Use Cases:

  • Shortening URLs for social media posts, emails, or QR codes.

  • Tracking clicks for marketing campaigns.

  • Limiting link lifetime using the expires_in parameter.

Request Body - example:

{
  "url": "https://google.com/",
  "expires_in": 3600
}

Response - example:

{
  "short_url": "http://localhost/r/HrTBms",
  "code": "HrTBms",
  "created_at": "2025-10-21T16:20:00.000Z",
  "expires_at": "2025-10-21T17:20:00.000Z"
}

How It Works:
1. Receives a JSON payload containing the original URL and optional expiration time.
2. Generates a unique 6-character code using SHA-256 hashing and Base62 encoding.
3. Checks the database to avoid code collisions.
4. Stores the original URL along with the short code and expiration timestamp in the database.
5. Returns a JSON object containing the short URL, code, and expiration datetime.

Implementation Highlights:
- Uses FastAPI for asynchronous handling of requests.
- SQLAlchemy AsyncSession ensures non-blocking database operations.
- Pydantic validates URL input and expiration parameters.
- Code generation is deterministic and collision-resistant.
- Optional expiration is handled by computing a future expires_at timestamp.