Python REST API Integration
Production-ready Python integration examples using requests and urllib with automatic rate limit backoff.
Python REST API Integration
Integrate Shortyy directly into Django, FastAPI, Flask, Celery, or data pipelines using standard Python HTTP libraries.
Requirements
bash
pip install requestsReusable Python Client Class
python
import os
import time
import requests
from typing import Optional, Dict, Any
class ShortyyClient:
def __init__(self, api_key: Optional[str] = None, base_url: str = "https://api.shortyy.com/v1"):
self.api_key = api_key or os.environ.get("SHORTYY_API_KEY")
if not self.api_key:
raise ValueError("SHORTYY_API_KEY is required")
self.base_url = base_url.rstrip("/")
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"User-Agent": "ShortyyPython/1.0",
})
def create_link(self, url: str, expires_in: str = "2h", custom_code: Optional[str] = None) -> Dict[str, Any]:
payload: Dict[str, Any] = {"url": url, "expires_in": expires_in}
if custom_code:
payload["custom_code"] = custom_code
response = self.session.post(f"{self.base_url}/links", json=payload, timeout=10.0)
# Handle rate limiting (HTTP 429)
if response.status_code == 429:
err = response.json().get("error", {})
retry_after = err.get("retryAfterSeconds") or int(response.headers.get("Retry-After", 60))
raise RuntimeError(f"Rate limited by Shortyy. Wait {retry_after}s.")
response.raise_for_status()
return response.json()["link"]
def get_analytics(self, link_id: str) -> Dict[str, Any]:
response = self.session.get(f"{self.base_url}/links/{link_id}/analytics", timeout=10.0)
response.raise_for_status()
return response.json()
# Usage Example:
if __name__ == "__main__":
client = ShortyyClient()
link = client.create_link("https://python.org", expires_in="1d")
print(f"Created short URL: {link['short_url']}")