> ## Documentation Index
> Fetch the complete documentation index at: https://docs.upwell.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Codes

> Complete reference for Upwell API error codes and troubleshooting

## Error Response Format

All Upwell API errors follow a consistent format to help you quickly identify and resolve issues:

```json theme={null}
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request contains invalid parameters",
    "details": {
      "field": "invoice_id",
      "issue": "Invoice ID must be a valid UUID"
    }
  },
  "status": "error",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

## HTTP Status Codes

| Status Code | Description           | Common Causes                                        |
| ----------- | --------------------- | ---------------------------------------------------- |
| `200`       | Success               | Request completed successfully                       |
| `201`       | Created               | Resource created successfully                        |
| `400`       | Bad Request           | Invalid request parameters or format                 |
| `401`       | Unauthorized          | Missing or invalid API key                           |
| `403`       | Forbidden             | Insufficient permissions for the requested operation |
| `404`       | Not Found             | Requested resource does not exist                    |
| `409`       | Conflict              | Resource already exists or conflicting operation     |
| `422`       | Unprocessable Entity  | Valid request format but invalid business logic      |
| `429`       | Too Many Requests     | Rate limit exceeded                                  |
| `500`       | Internal Server Error | Server-side error occurred                           |
| `503`       | Service Unavailable   | API temporarily unavailable                          |

## Common Error Codes

### Authentication Errors

<AccordionGroup>
  <Accordion icon="key" title="INVALID_API_KEY">
    **HTTP Status**: 401
    **Description**: The provided API key is invalid or expired
    **Solution**: Verify your API key and regenerate if necessary

    ```json theme={null}
    {
      "error": {
        "code": "INVALID_API_KEY",
        "message": "The provided API key is invalid"
      }
    }
    ```
  </Accordion>

  <Accordion icon="lock" title="MISSING_AUTHORIZATION">
    **HTTP Status**: 401
    **Description**: Authorization header is missing from the request
    **Solution**: Include your API key in the Authorization header

    ```json theme={null}
    {
      "error": {
        "code": "MISSING_AUTHORIZATION",
        "message": "Authorization header is required"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

### Validation Errors

<AccordionGroup>
  <Accordion icon="exclamation-triangle" title="VALIDATION_ERROR">
    **HTTP Status**: 400
    **Description**: Request contains invalid or missing required parameters
    **Solution**: Check the details field for specific validation issues

    ```json theme={null}
    {
      "error": {
        "code": "VALIDATION_ERROR",
        "message": "Validation failed for one or more fields",
        "details": [
          {
            "field": "customer_id",
            "message": "Customer ID is required"
          },
          {
            "field": "amount",
            "message": "Amount must be greater than 0"
          }
        ]
      }
    }
    ```
  </Accordion>

  <Accordion icon="calendar" title="INVALID_DATE_FORMAT">
    **HTTP Status**: 400
    **Description**: Date parameter is not in the expected format
    **Solution**: Use ISO 8601 format (YYYY-MM-DDTHH:mm:ssZ)

    ```json theme={null}
    {
      "error": {
        "code": "INVALID_DATE_FORMAT",
        "message": "Date must be in ISO 8601 format"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

### Resource Errors

<AccordionGroup>
  <Accordion icon="search" title="RESOURCE_NOT_FOUND">
    **HTTP Status**: 404
    **Description**: The requested resource does not exist
    **Solution**: Verify the resource ID and ensure it exists

    ```json theme={null}
    {
      "error": {
        "code": "RESOURCE_NOT_FOUND",
        "message": "Invoice with ID 'abc123' not found"
      }
    }
    ```
  </Accordion>

  <Accordion icon="copy" title="RESOURCE_ALREADY_EXISTS">
    **HTTP Status**: 409
    **Description**: Attempting to create a resource that already exists
    **Solution**: Use PUT to update existing resource or check for duplicates

    ```json theme={null}
    {
      "error": {
        "code": "RESOURCE_ALREADY_EXISTS",
        "message": "Invoice with this number already exists"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

### Business Logic Errors

<AccordionGroup>
  <Accordion icon="ban" title="INVOICE_ALREADY_APPROVED">
    **HTTP Status**: 422
    **Description**: Attempting to modify an invoice that has already been approved
    **Solution**: Only draft invoices can be modified

    ```json theme={null}
    {
      "error": {
        "code": "INVOICE_ALREADY_APPROVED",
        "message": "Cannot modify an approved invoice"
      }
    }
    ```
  </Accordion>

  <Accordion icon="credit-card" title="INSUFFICIENT_CREDIT_LIMIT">
    **HTTP Status**: 422
    **Description**: Customer's credit limit would be exceeded
    **Solution**: Increase credit limit or collect payment before proceeding

    ```json theme={null}
    {
      "error": {
        "code": "INSUFFICIENT_CREDIT_LIMIT",
        "message": "Customer credit limit exceeded"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

### Rate Limiting Errors

<AccordionGroup>
  <Accordion icon="clock" title="RATE_LIMIT_EXCEEDED">
    **HTTP Status**: 429
    **Description**: Too many requests in a short time period
    **Solution**: Implement exponential backoff and respect rate limits

    ```json theme={null}
    {
      "error": {
        "code": "RATE_LIMIT_EXCEEDED",
        "message": "Rate limit exceeded. Try again in 60 seconds",
        "details": {
          "retry_after": 60,
          "limit": 100,
          "window": "1 hour"
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Rate Limiting

The Upwell API implements rate limiting to ensure fair usage and system stability:

* **Standard Rate Limit**: 100 requests per hour per API key
* **Burst Limit**: 10 requests per minute
* **Rate Limit Headers**: Check response headers for current limits

```http theme={null}
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1642248000
```

## Error Handling Best Practices

### 1. Implement Retry Logic

```javascript theme={null}
async function apiCall(url, options, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);

      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After') || Math.pow(2, attempt);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

      if (!response.ok) {
        const error = await response.json();
        throw new Error(`API Error: ${error.error.message}`);
      }

      return await response.json();
    } catch (error) {
      if (attempt === maxRetries) throw error;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
    }
  }
}
```

### 2. Validate Input Data

```python theme={null}
def validate_invoice_data(invoice_data):
    required_fields = ['customer_id', 'amount', 'due_date']

    for field in required_fields:
        if field not in invoice_data:
            raise ValueError(f"Missing required field: {field}")

    if invoice_data['amount'] <= 0:
        raise ValueError("Amount must be greater than 0")

    # Additional validation logic...
```

### 3. Handle Specific Error Codes

```python theme={null}
import requests

def handle_api_response(response):
    if response.status_code == 200:
        return response.json()

    error_data = response.json().get('error', {})
    error_code = error_data.get('code')

    if error_code == 'INVALID_API_KEY':
        # Regenerate API key
        refresh_api_key()
    elif error_code == 'RATE_LIMIT_EXCEEDED':
        # Wait and retry
        retry_after = error_data.get('details', {}).get('retry_after', 60)
        time.sleep(retry_after)
    elif error_code == 'RESOURCE_NOT_FOUND':
        # Handle missing resource
        return None
    else:
        # Log unexpected error
        logger.error(f"API Error: {error_data.get('message')}")

    raise Exception(f"API Error: {error_data.get('message')}")
```

## Getting Help

If you encounter persistent errors or need assistance:

1. **Check this documentation** for common solutions
2. **Review API logs** for detailed error information
3. **Contact support** at [support@upwell.com](mailto:support@upwell.com)
4. **Include error details** and request IDs when reporting issues

For urgent issues, please include:

* API endpoint being called
* Complete error response
* Request timestamp
* Your API key (last 4 characters only)
