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 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 URLPOST /login- Authenticate and receive access tokenGET /{url_code}- Redirect to original URLGET /- Welcome messageGET /health- Health check
Protected Endpoints
These endpoints require a valid Bearer token in theAuthorization header:
POST /change_password- Change URL passwordDELETE /delete- Delete a short URLPATCH /pause- Pause URL redirectsPATCH /resume- Resume URL redirectsPATCH /reset_hits- Reset hit counterPATCH /change_url- Change redirect destinationGET /details- Get URL statistics and detailsGET /validate_token- Validate access tokenGET /refresh_token- Refresh access token
Response Format
All API responses return JSON with a consistent structure.Success Response
Error Response
HTTP Status Codes
The API uses standard HTTP status codes to indicate success or failure:| Status Code | Meaning | Usage |
|---|---|---|
200 | OK | Successful GET/PATCH request |
201 | Created | URL successfully created |
400 | Bad Request | Invalid input, blacklisted URL, invalid code/password format |
401 | Unauthorized | Invalid credentials or authentication failure |
403 | Forbidden | Missing or expired token |
404 | Not Found | URL not found or database connection failed |
409 | Conflict | URL code already exists |
423 | Locked | URL redirect is temporarily paused |
Error Handling
The API implements comprehensive error handling for common scenarios:URL Code Validation Errors
URL Code Validation Errors
- URL codes must be 3-20 characters (alphanumeric, hyphens, underscores)
- Reserved keywords cannot be used as URL codes
- Returns
400 Bad Requestwith message: “Invalid URL code”
Password Validation Errors
Password Validation Errors
- Passwords must be 0 (no password) or 3-20 characters
- Returns
400 Bad Requestwith message: “Password length must be 3..20”
URL Blacklist Errors
URL Blacklist Errors
- URLs containing blacklisted domains are rejected
- Returns
400 Bad Requestwith message: “URL Blacklisted”
Duplicate URL Code
Duplicate URL Code
- URL codes must be unique
- Returns
409 Conflictwith message: “URL code already exists”
Authentication Errors
Authentication Errors
- 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 capabilitiesReDoc
Available at:
/redocClean, three-panel documentation with detailed schema informationAPI Endpoints Reference
URL Management
Create Short URL
POST /createCreate a new short URL with optional password protectionRedirect
GET /{url_code}Redirect to the original URL and track analyticsDelete URL
DELETE /deletePermanently delete a short URL and its statisticsChange Redirect URL
PATCH /change_urlUpdate the destination URL for an existing short codeAuthentication
Login
POST /loginAuthenticate with URL code and password to receive access tokenChange Password
POST /change_passwordChange the password for a protected URLValidate Token
GET /validate_tokenVerify if an access token is validRefresh Token
GET /refresh_tokenGenerate a new access token from an existing valid tokenURL Control
Pause Redirects
PATCH /pauseTemporarily disable redirects for a URL (returns 423 status)Resume Redirects
PATCH /resumeRe-enable redirects for a paused URLReset Hit Counter
PATCH /reset_hitsReset the analytics hit counter to zeroGet Details
GET /detailsRetrieve URL statistics and configuration detailsSystem
Health Check
GET /healthVerify database connectivity and API healthGetting Started
To start using the Short-URL API:- Create a Short URL - Use
POST /createto create your first short URL - Test the Redirect - Visit
{SURL_BASE}/{url_code}to test the redirect - Add Password Protection - Create URLs with passwords for management capabilities
- Authenticate - Use
POST /loginto get an access token - Manage URLs - Use protected endpoints to pause, resume, update, or delete URLs
- Track Analytics - Use
GET /detailsto 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 theALLOWED_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,resumedetails,refresh_token,change_password,reset_hitschange_url,validate_token,health
URL Blacklist
The API supports URL blacklisting via theURL_BLACKLIST environment variable. URLs containing any blacklisted domain or pattern will be rejected with a 400 Bad Request error.