Skip to main content

Introduction

The Short-URL API is a modern, asynchronous REST API built with FastAPI that provides URL shortening services with password protection, analytics tracking, and comprehensive URL management capabilities.
The API is fully async and built on top of FastAPI, providing high performance and automatic OpenAPI documentation.

Base URL

All API requests are made to your configured base URL:
{SURL_BASE}
This base URL is configured via the SURL_BASE environment variable and is used to construct short URLs.

API Design Principles

RESTful Architecture

Standard HTTP methods (GET, POST, PATCH, DELETE) with intuitive endpoint naming

Asynchronous Processing

Built with FastAPI and Motor for high-performance async operations

MongoDB Backend

Uses MongoDB with async driver for scalable data storage

Type Safety

Pydantic models ensure request/response validation

Authentication

The API uses Bearer Token Authentication for protected endpoints.

Public Endpoints

These endpoints do not require authentication:
  • POST /create - Create a new short URL
  • POST /login - Authenticate and receive access token
  • GET /{url_code} - Redirect to original URL
  • GET / - Welcome message
  • GET /health - Health check

Protected Endpoints

These endpoints require a valid Bearer token in the Authorization header:
  • POST /change_password - Change URL password
  • DELETE /delete - Delete a short URL
  • PATCH /pause - Pause URL redirects
  • PATCH /resume - Resume URL redirects
  • PATCH /reset_hits - Reset hit counter
  • PATCH /change_url - Change redirect destination
  • GET /details - Get URL statistics and details
  • GET /validate_token - Validate access token
  • GET /refresh_token - Refresh access token
Access tokens are JWT-based and contain the URL ID. Only password-protected URLs can generate tokens.

Response Format

All API responses return JSON with a consistent structure.

Success Response

{
  "message": "Operation successful",
  "short_url": "{SURL_BASE}/mycode",
  "data": {...}
}

Error Response

{
  "detail": "Error description"
}

HTTP Status Codes

The API uses standard HTTP status codes to indicate success or failure:
Status CodeMeaningUsage
200OKSuccessful GET/PATCH request
201CreatedURL successfully created
400Bad RequestInvalid input, blacklisted URL, invalid code/password format
401UnauthorizedInvalid credentials or authentication failure
403ForbiddenMissing or expired token
404Not FoundURL not found or database connection failed
409ConflictURL code already exists
423LockedURL redirect is temporarily paused

Error Handling

The API implements comprehensive error handling for common scenarios:
  • URL codes must be 3-20 characters (alphanumeric, hyphens, underscores)
  • Reserved keywords cannot be used as URL codes
  • Returns 400 Bad Request with message: “Invalid URL code”
  • Passwords must be 0 (no password) or 3-20 characters
  • Returns 400 Bad Request with message: “Password length must be 3..20”
  • URLs containing blacklisted domains are rejected
  • Returns 400 Bad Request with message: “URL Blacklisted”
  • URL codes must be unique
  • Returns 409 Conflict with message: “URL code already exists”
  • Invalid or missing credentials return 401 Unauthorized
  • Expired or invalid tokens return 403 Forbidden
  • Requests without required authentication return 403 Unauthorized

Rate Limiting

The API does not currently implement rate limiting at the application level. Consider implementing rate limiting at the infrastructure level (reverse proxy, API gateway) for production deployments.

Interactive Documentation

FastAPI provides automatic interactive API documentation:

Swagger UI

Available at: /docsInteractive API explorer with request/response examples and testing capabilities

ReDoc

Available at: /redocClean, three-panel documentation with detailed schema information

API Endpoints Reference

URL Management

Create Short URL

POST /createCreate a new short URL with optional password protection

Redirect

GET /{url_code}Redirect to the original URL and track analytics

Delete URL

DELETE /deletePermanently delete a short URL and its statistics

Change Redirect URL

PATCH /change_urlUpdate the destination URL for an existing short code

Authentication

Login

POST /loginAuthenticate with URL code and password to receive access token

Change Password

POST /change_passwordChange the password for a protected URL

Validate Token

GET /validate_tokenVerify if an access token is valid

Refresh Token

GET /refresh_tokenGenerate a new access token from an existing valid token

URL Control

Pause Redirects

PATCH /pauseTemporarily disable redirects for a URL (returns 423 status)

Resume Redirects

PATCH /resumeRe-enable redirects for a paused URL

Reset Hit Counter

PATCH /reset_hitsReset the analytics hit counter to zero

Get Details

GET /detailsRetrieve URL statistics and configuration details

System

Health Check

GET /healthVerify database connectivity and API health

Getting Started

To start using the Short-URL API:
  1. Create a Short URL - Use POST /create to create your first short URL
  2. Test the Redirect - Visit {SURL_BASE}/{url_code} to test the redirect
  3. Add Password Protection - Create URLs with passwords for management capabilities
  4. Authenticate - Use POST /login to get an access token
  5. Manage URLs - Use protected endpoints to pause, resume, update, or delete URLs
  6. Track Analytics - Use GET /details to view hit counts and URL statistics

Quick Start Guide

Follow our quickstart guide for detailed setup instructions and example requests

CORS Configuration

The API supports Cross-Origin Resource Sharing (CORS) with configurable origins via the ALLOWED_ORIGINS environment variable. By default, all origins are allowed (*).

URL Code Restrictions

URL codes have specific requirements and restrictions:
  • Length: 3-20 characters
  • Allowed characters: Alphanumeric (A-Z, a-z, 0-9), hyphens (-), underscores (_)
  • Reserved keywords: The following cannot be used as URL codes:
    • docs, redoc, create, login, delete, pause, resume
    • details, refresh_token, change_password, reset_hits
    • change_url, validate_token, health

URL Blacklist

The API supports URL blacklisting via the URL_BLACKLIST environment variable. URLs containing any blacklisted domain or pattern will be rejected with a 400 Bad Request error.

Background Processing

The API uses FastAPI’s background tasks for non-blocking analytics updates. Hit counters are incremented asynchronously after redirects complete, ensuring fast redirect responses.

Build docs developers (and LLMs) love