> For the complete documentation index, see [llms.txt](https://4ns-organization.gitbook.io/4n.eco/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://4ns-organization.gitbook.io/4n.eco/url-shortening-api-documentation.md).

# URL Shortening API Documentation

### Overview

The URL Shortening API enables authenticated users to convert long URLs into short, user-friendly links. It includes built-in rate limiting (100 requests per 24 hours per API key) and error handling to ensure smooth integration into your applications.

**Base Production URL:**

```
https://4n.eco
```

### Authentication

All API requests must be authenticated using a valid API key.

* **Header Name:** `x-api-key`
* **Header Value:** Your API key (e.g., `<YOUR_API_KEY>`)

Keep your API key secure and do not expose it publicly.

### Endpoint

**GET** `/api/shorten-public`

This endpoint shortens a provided URL. You may supply an optional custom alias; if omitted, an alias will be automatically generated.

#### Query Parameters

* **originalUrl** (required)\
  The long URL that you wish to shorten.
* **alias** (optional)\
  A custom alias for the shortened URL.\
  **Note:** If the alias is already in use, the API returns an error.

### Request Examples

#### 1. Using a Custom Alias

**cURL (Single Line - Windows/Unix):**

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com&alias=mycustomalias" -H "x-api-key: <YOUR_API_KEY>"
```

**Expected Response (HTTP 200):**

```json
{
  "shortenedUrl": "https://4n.eco/mycustomalias"
}
```

#### 2. Using an Auto-Generated Alias

**cURL:**

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com" -H "x-api-key: <YOUR_API_KEY>"
```

**Expected Response (HTTP 200):**

```json
{
  "shortenedUrl": "https://4n.eco/<generated_alias>"
}
```

### Error Responses

* **Missing Required Parameter (originalUrl):**

  **Response:**

  ```json
  {
    "error": "URL is required"
  }
  ```

  **HTTP Status:** 400
* **Alias Already in Use:**

  **Response:**

  ```json
  {
    "error": "Alias already in use. Try another alias."
  }
  ```

  **HTTP Status:** 409
* **Invalid API Key:**

  **Response:**

  ```json
  {
    "error": "Invalid API key"
  }
  ```

  **HTTP Status:** 401
* **Rate Limit Exceeded:**

  **Response:**

  ```json
  {
    "error": "API rate limit exceeded. Please try again later."
  }
  ```

  **HTTP Status:** 429

### Testing Scenarios

Below are sample cURL commands for testing various scenarios. Replace `<YOUR_API_KEY>` with your actual API key when testing.

#### Valid Request with a Custom Alias

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com&alias=mycustomalias" -H "x-api-key: <YOUR_API_KEY>"
```

#### Valid Request Without Providing an Alias

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com" -H "x-api-key: <YOUR_API_KEY>"
```

#### Missing Required Parameter (originalUrl)

```bash
curl -X GET "https://4n.eco/api/shorten-public?alias=testalias" -H "x-api-key: <YOUR_API_KEY>"
```

#### Alias Already in Use

**Step 1: Create a shortened URL**

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com&alias=duplicatealias" -H "x-api-key: <YOUR_API_KEY>"
```

**Step 2: Attempt to use the same alias again**

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com&alias=duplicatealias" -H "x-api-key: <YOUR_API_KEY>"
```

#### Invalid API Key

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com&alias=invalidtest" -H "x-api-key: INVALID_API_KEY"
```

#### Rate Limiting (Optional Test)

Run this command repeatedly to simulate exceeding 100 requests in 24 hours:

```bash
curl -X GET "https://4n.eco/api/shorten-public?originalUrl=https://www.google.com&alias=ratelimittest" -H "x-api-key: <YOUR_API_KEY>"
```

### Integration Examples

#### JavaScript (Using Fetch)

Integrate the API directly in your web application with a simple fetch request:

```javascript
const shortenUrl = async (originalUrl, alias = '') => {
  const url = new URL('https://4n.eco/api/shorten-public');
  url.searchParams.append('originalUrl', originalUrl);
  if (alias) {
    url.searchParams.append('alias', alias);
  }

  try {
    const response = await fetch(url.toString(), {
      method: 'GET',
      headers: {
        'x-api-key': '<YOUR_API_KEY>'
      }
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error);
    }
    
    const data = await response.json();
    console.log('Shortened URL:', data.shortenedUrl);
    return data.shortenedUrl;
  } catch (error) {
    console.error('Error shortening URL:', error.message);
  }
};

// Example usage:
shortenUrl('https://www.google.com', 'mycustomalias');
```

#### Python (Using Requests)

Use Python's requests library to integrate the API into your backend application:

```python
import requests

def shorten_url(original_url, alias=None):
    base_url = 'https://4n.eco/api/shorten-public'
    params = {'originalUrl': original_url}
    if alias:
        params['alias'] = alias

    headers = {
        'x-api-key': '<YOUR_API_KEY>'
    }

    response = requests.get(base_url, params=params, headers=headers)
    if response.status_code == 200:
        data = response.json()
        print('Shortened URL:', data['shortenedUrl'])
        return data['shortenedUrl']
    else:
        print('Error:', response.json()['error'])
        return None

# Example usage:
shorten_url('https://www.google.com', 'mycustomalias')
```

### Integration Notes

* **Error Handling:**\
  Check the HTTP status code and error messages in your integration code to handle errors gracefully.
* **Security:**\
  Never expose your API key in publicly accessible code. Use environment variables or secure storage.
* **Rate Limits:**\
  If your application might exceed 100 requests per day, implement retry logic or notify users of the limit.
* **Custom vs. Auto-Generated Alias:**\
  If you don’t require a specific alias, omitting the alias parameter allows the API to generate one automatically.

### Conclusion

The URL Shortening API provides a straightforward and secure method to generate short URLs. With detailed error responses, built-in rate limiting, and flexible aliasing, developers can easily integrate this service into web or backend applications. For further assistance or to report issues, please contact our support team.
