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.

📄Create Short Link | JavaScript
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});
📄Create Short Link | Python
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}")
📄Create Short Link | cURL
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}

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)

📄Create QR Code | JavaScript
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)

📄Click Analytics | JavaScript
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

📄Create API Key | JavaScript
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.

Security
  • • 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
Performance
  • • 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
Error Handling
  • • 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
Code Organization
  • • 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.

Next steps:
  1. Create an API key in your Cutly dashboard
  2. Test the examples with your API key
  3. Implement error handling and retry logic
  4. 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

Examples | Documentation