Examples
Practical examples and code snippets for integrating with the Cutly API. Learn how to use our API with JavaScript, Python, cURL, and more.
Quick Start
Get started quickly with these basic examples. Make sure you have created an API key from your dashboard first.
Authentication Required
All API endpoints require authentication using your API key. Include it in the X-API-Key
header.
1// Create a short link
2async function createShortLink(originalUrl, options = {}) {
3 try {
4 const response = await fetch('https://cutly.xyz/api/v1/short-links', {
5 method: 'POST',
6 headers: {
7 'Content-Type': 'application/json',
8 'X-API-Key': 'your_api_key_here'
9 },
10 body: JSON.stringify({
11 original_url: originalUrl,
12 title: options.title,
13 description: options.description,
14 custom_alias: options.customAlias,
15 tags: options.tags
16 })
17 });
18
19 const data = await response.json();
20
21 if (!response.ok) {
22 throw new Error(data.error || 'Failed to create short link');
23 }
24
25 return data;
26 } catch (error) {
27 console.error('Error creating short link:', error);
28 throw error;
29 }
30}
31
32// Usage
33createShortLink('https://example.com/very-long-url', {
34 title: 'My Example Link',
35 description: 'A test link',
36 tags: ['example', 'test']
37}).then(result => {
38 console.log('Short URL:', result.data.short_url);
39}).catch(error => {
40 console.error('Failed:', error.message);
41});
1import requests
2import json
3
4class CutlyAPI:
5 def __init__(self, api_key):
6 self.api_key = api_key
7 self.base_url = "https://cutly.xyz"
8 self.headers = {
9 "Content-Type": "application/json",
10 "X-API-Key": api_key
11 }
12
13 def create_short_link(self, original_url, **kwargs):
14 """Create a new short link"""
15 payload = {
16 "original_url": original_url,
17 **kwargs
18 }
19
20 response = requests.post(
21 f"{self.base_url}/api/v1/short-links",
22 headers=self.headers,
23 json=payload
24 )
25
26 if response.status_code != 200:
27 raise Exception(f"API Error: {response.json().get('error', 'Unknown error')}")
28
29 return response.json()
30
31# Usage
32api = CutlyAPI("your_api_key_here")
33
34try:
35 result = api.create_short_link(
36 "https://example.com/very-long-url",
37 title="My Example Link",
38 description="A test link",
39 tags=["example", "test"]
40 )
41 print(f"Short URL: {result['data']['short_url']}")
42except Exception as e:
43 print(f"Error: {e}")
1# Create a short link
2curl -X POST "https://cutly.xyz/api/v1/short-links" \
3 -H "Content-Type: application/json" \
4 -H "X-API-Key: your_api_key_here" \
5 -d '{
6 "original_url": "https://example.com/very-long-url",
7 "title": "My Example Link",
8 "description": "A test link",
9 "tags": ["example", "test"]
10 }'
11
12# Response
13{
14 "success": true,
15 "data": {
16 "id": "uuid-here",
17 "short_code": "abc123",
18 "original_url": "https://example.com/very-long-url",
19 "short_url": "https://cutly.xyz/r/abc123",
20 "created_at": "2024-01-01T00:00:00Z"
21 }
22}
Short Links API
Comprehensive examples for managing short links - create, list, update, and delete.
Create Short Link
1const cutlyAPI = {
2 baseUrl: 'https://cutly.xyz',
3 apiKey: 'your_api_key_here',
4
5 async createShortLink(data) {
6 const response = await fetch(`${this.baseUrl}/api/v1/short-links`, {
7 method: 'POST',
8 headers: {
9 'Content-Type': 'application/json',
10 'X-API-Key': this.apiKey
11 },
12 body: JSON.stringify(data)
13 });
14
15 if (!response.ok) {
16 const error = await response.json();
17 throw new Error(error.error || 'Failed to create short link');
18 }
19
20 return await response.json();
21 }
22};
23
24// Create with custom alias
25const result = await cutlyAPI.createShortLink({
26 original_url: 'https://example.com/product/12345',
27 custom_alias: 'product-12345',
28 title: 'Amazing Product',
29 description: 'Check out this amazing product!',
30 tags: ['product', 'marketing']
31});
32
33console.log('Created:', result.data.short_url);
1import requests
2
3def create_short_link(api_key, original_url, **kwargs):
4 """Create a short link with optional parameters"""
5 url = "https://cutly.xyz/api/v1/short-links"
6 headers = {
7 "Content-Type": "application/json",
8 "X-API-Key": api_key
9 }
10
11 payload = {
12 "original_url": original_url,
13 **kwargs
14 }
15
16 response = requests.post(url, headers=headers, json=payload)
17 response.raise_for_status()
18
19 return response.json()
20
21# Create with custom alias
22result = create_short_link(
23 api_key="your_api_key_here",
24 original_url="https://example.com/product/12345",
25 custom_alias="product-12345",
26 title="Amazing Product",
27 description="Check out this amazing product!",
28 tags=["product", "marketing"]
29)
30
31print(f"Created: {result['data']['short_url']}")
1curl -X POST "https://cutly.xyz/api/v1/short-links" \
2 -H "Content-Type: application/json" \
3 -H "X-API-Key: your_api_key_here" \
4 -d '{
5 "original_url": "https://example.com/product/12345",
6 "custom_alias": "product-12345",
7 "title": "Amazing Product",
8 "description": "Check out this amazing product!",
9 "tags": ["product", "marketing"]
10 }'
List Short Links
1async function listShortLinks(options = {}) {
2 const params = new URLSearchParams();
3
4 if (options.limit) params.append('limit', options.limit);
5 if (options.offset) params.append('offset', options.offset);
6 if (options.search) params.append('search', options.search);
7
8 const response = await fetch(`https://cutly.xyz/api/v1/short-links?${params}`, {
9 headers: {
10 'X-API-Key': 'your_api_key_here'
11 }
12 });
13
14 return await response.json();
15}
16
17// List with pagination and search
18const links = await listShortLinks({
19 limit: 20,
20 offset: 0,
21 search: 'product'
22});
23
24console.log(`Found ${links.data.length} links`);
25links.data.forEach(link => {
26 console.log(`${link.title}: ${link.short_url}`);
27});
1def list_short_links(api_key, limit=50, offset=0, search=None):
2 """List short links with pagination and search"""
3 url = "https://cutly.xyz/api/v1/short-links"
4 headers = {"X-API-Key": api_key}
5
6 params = {
7 "limit": limit,
8 "offset": offset
9 }
10
11 if search:
12 params["search"] = search
13
14 response = requests.get(url, headers=headers, params=params)
15 response.raise_for_status()
16
17 return response.json()
18
19# List with search
20links = list_short_links(
21 api_key="your_api_key_here",
22 limit=20,
23 search="product"
24)
25
26print(f"Found {len(links['data'])} links")
27for link in links['data']:
28 print(f"{link['title']}: {link['short_url']}")
1# List all short links
2curl -H "X-API-Key: your_api_key_here" \
3 "https://cutly.xyz/api/v1/short-links"
4
5# List with pagination and search
6curl -H "X-API-Key: your_api_key_here" \
7 "https://cutly.xyz/api/v1/short-links?limit=20&offset=0&search=product"
QR Codes API
Generate and manage QR codes for your short links with customization options.
Note
QR code endpoints currently require web authentication. API key support for QR codes is coming soon.
Create QR Code (Web Auth Required)
1// Note: This requires web authentication, not API key
2async function createQRCode(shortLinkId, options = {}) {
3const response = await fetch('https://cutly.xyz/api/qr-codes', {
4method: 'POST',
5headers: {
6 'Content-Type': 'application/json',
7 // Web session authentication required
8},
9body: JSON.stringify({
10 short_link_id: shortLinkId,
11 name: options.name || 'My QR Code',
12 size: options.size || 300,
13 foreground_color: options.foregroundColor || '#000000',
14 background_color: options.backgroundColor || '#FFFFFF',
15 corner_square_color: options.cornerSquareColor || '#000000',
16 corner_dot_color: options.cornerDotColor || '#000000',
17 logo_url: options.logoUrl,
18 logo_filename: options.logoFilename,
19 settings: options.settings || {}
20})
21});
22
23return await response.json();
24}
Analytics API
Access click analytics and API usage data for your account.
Click Analytics (Web Auth Required)
1// Note: Currently requires web authentication
2async function getClickAnalytics(options = {}) {
3const params = new URLSearchParams();
4
5if (options.limit) params.append('limit', options.limit);
6if (options.offset) params.append('offset', options.offset);
7
8const response = await fetch(`https://cutly.xyz/api/click-analytics?${params}`, {
9headers: {
10 // Web session authentication required
11}
12});
13
14return await response.json();
15}
16
17// Get recent clicks
18const analytics = await getClickAnalytics({ limit: 100 });
19console.log(`Total clicks: ${analytics.data.length}`);
API Keys Management
Manage your API keys programmatically. Note: These endpoints require web authentication.
Web Authentication Required
API key management endpoints require web session authentication, not API key authentication.
Create API Key
1async function createAPIKey(name) {
2const response = await fetch('https://cutly.xyz/api/api-keys', {
3method: 'POST',
4headers: {
5 'Content-Type': 'application/json',
6 // Web session authentication required
7},
8body: JSON.stringify({
9 name: name
10})
11});
12
13const result = await response.json();
14
15if (result.success) {
16// IMPORTANT: Save the API key immediately!
17// It's only shown once and cannot be retrieved later
18console.log('API Key:', result.data.api_key);
19console.log('Key ID:', result.data.id);
20console.log('Prefix:', result.data.key_prefix);
21}
22
23return result;
24}
25
26// Create new API key
27const newKey = await createAPIKey('My Integration Key');
Error Handling
Comprehensive error handling examples for robust API integration.
Common Error Responses
401
Unauthorized{ "error": "API key is required" }
400
Bad Request{ "error": "original_url is required" }
409
Conflict{ "error": "Custom alias already exists" }
429
Rate Limited{ "error": "Rate limit exceeded", "retry_after": 60 }
Best Practices
Follow these best practices for reliable and efficient API integration.
- • Store API keys securely using environment variables
- • Never expose API keys in client-side code
- • Rotate API keys regularly
- • Use HTTPS for all API requests
- • Implement proper access controls in your application
- • Implement retry logic with exponential backoff for rate limits
- • Use pagination for large datasets
- • Cache responses when appropriate
- • Implement request timeouts
- • Monitor your API usage to stay within limits
- • Always check response status codes
- • Handle network errors gracefully
- • Implement proper logging for debugging
- • Provide meaningful error messages to users
- • Test error scenarios in your application
- • Create a dedicated API client class or module
- • Use TypeScript for better type safety
- • Implement consistent error handling across your app
- • Add comprehensive tests for your API integration
- • Document your API usage for team members
Ready to Get Started?
You now have comprehensive examples for integrating with the Cutly API. Start by creating an API key in your dashboard, then use these examples as a foundation for your integration.
- Create an API key in your Cutly dashboard
- Test the examples with your API key
- Implement error handling and retry logic
- Build your integration using these patterns
Getting Help
Email Support
Get detailed help via email
support@cutly.com
Response within 24 hours
Live Chat
Instant help from our Chatbot
Available 24/7
Pro+ users only
Documentation
Comprehensive guides and examples
Always Available
Self-service help
Can't find what you're looking for? Contact our support team