# Error Handling

The HG Insights API uses standard HTTP status codes and provides detailed error messages to help you diagnose and resolve issues quickly.

## Error Response Structure

All error responses follow a consistent JSON structure:


```json
{
  "errors": [
    {
      "title": "Invalid request",
      "detail": "The request is invalid",
      "source": {
        "pointer": "/data/attributes/field-name"
      }
    }
  ]
}
```

Each error object contains:

- **title**: A short, human-readable summary of the problem
- **detail**: A detailed explanation of the error
- **source**: (Optional) The location in the request that caused the error


> **Note**: The `source` field structure varies by error type. For validation errors (422) it is an object with a `pointer` property. For authentication (401) and service availability (503) errors it is a nullable string or omitted.


## HTTP Status Codes

The API uses standard HTTP status codes to indicate success or failure:

| Code | Description | What It Means |
|  --- | --- | --- |
| 200 | OK | Request was successful |
| 400 | Bad Request | The request body is malformed or contains invalid JSON |
| 401 | Unauthorized | Missing or invalid API key, or access denied to requested field groups |
| 422 | Unprocessable Entity | Request validation failed (missing or invalid parameters) |
| 429 | Too Many Requests | Rate limit exceeded — back off and retry |
| 500 | Internal Server Error | An unexpected error occurred on the server |
| 503 | Service Unavailable | A dependent service is temporarily unavailable |


## Common Error Scenarios

### 1. Authentication Errors (401)

**Problem**: Missing or invalid API key


```json
{
  "errors": [{
    "title": "Unauthorized",
    "detail": "Invalid or missing API key"
  }]
}
```

**Solution**:

- Verify your API key is correct
- Ensure you're using the `Authorization: Bearer YOUR_API_KEY` header format
- Check that your API key starts with `hg_v2_`


**Problem**: Access denied to field groups


```json
{
  "errors": [{
    "title": "Unauthorized",
    "detail": "Access denied to field group: technographics"
  }]
}
```

**Solution**:

- Contact us at customersupport@hginsights.com to upgrade your field group entitlements
- Remove the restricted field group from your request


### 2. Validation Errors (422)

**Problem**: Missing required parameters


```json
{
  "errors": [{
    "title": "Validation failed",
    "detail": "companies.ids is required",
    "source": {
      "pointer": "/companies/ids"
    }
  }]
}
```

**Solution**:

- Check the `source.pointer` to identify the problematic field
- Ensure all required parameters are included in your request
- Refer to the [API Reference](/v2/openapi) for parameter requirements


**Problem**: Invalid parameter values


```json
{
  "errors": [{
    "title": "Validation failed",
    "detail": "companies.ids exceeds maximum of 25 items",
    "source": {
      "pointer": "/companies/ids"
    }
  }]
}
```

**Solution**:

- Review parameter constraints (e.g., max array length, valid values)
- Split large requests into multiple batches if needed


### 3. Server Errors (500, 503)

**Problem**: Unexpected server error


```json
{
  "errors": [{
    "title": "Internal Server Error",
    "detail": "An unexpected error occurred"
  }]
}
```

**Problem**: Service temporarily unavailable (e.g., credit verification failure)


```json
{
  "errors": [{
    "title": "Service unavailable",
    "detail": "Unable to verify credit availability. Please try again later. If the error persists, contact customersupport@hginsights.com."
  }]
}
```

**Solution**:

- Retry the request with exponential backoff
- If the error persists, contact HG Insights support with the request details


## Best Practices

### 1. Implement Retry Logic

For transient errors (500, 503) and rate limit errors (429), implement exponential backoff:


```python
import time
import requests

def make_request_with_retry(url, headers, data, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(url, headers=headers, json=data)

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

        if response.status_code == 429:
            # Rate limited - retry with exponential backoff
            wait_time = 2 ** attempt  # 1s, 2s, 4s
            time.sleep(wait_time)
            continue

        if response.status_code >= 500:
            # Server error - retry with exponential backoff
            wait_time = 2 ** attempt  # 1s, 2s, 4s
            time.sleep(wait_time)
            continue

        # Client error - don't retry
        response.raise_for_status()

    raise Exception("Max retries exceeded")
```

### 2. Log Error Details

Always log the full error response for debugging:


```javascript
try {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(requestData)
  });

  if (!response.ok) {
    const errorData = await response.json();
    console.error('API Error:', {
      status: response.status,
      errors: errorData.errors
    });
    throw new Error(`API request failed: ${response.status}`);
  }

  return await response.json();
} catch (error) {
  console.error('Request failed:', error);
  throw error;
}
```

## Troubleshooting Checklist

If you're experiencing errors, check:

- ✅ API key is valid and properly formatted
- ✅ Authorization header is included: `Authorization: Bearer YOUR_API_KEY`
- ✅ Request body is valid JSON
- ✅ All required parameters are included
- ✅ Parameter values meet validation requirements
- ✅ Field groups requested are included in your subscription
- ✅ Base URL is correct: `https://api.hginsights.com/data-api/v2`
- ✅ Content-Type header is set: `Content-Type: application/json`


## Getting Help

If you continue experiencing errors:

1. Check the error message and `source.pointer` for specific guidance
2. Review the [API Reference](/v2/openapi) for parameter specifications
3. Consult the [Authentication](/v2/guides/authentication) and [Enrichment](/v2/guides/enrichment) guides
4. Contact us at customersupport@hginsights.com for support


Include the following information when reporting issues:

- Full error response
- Request details (URL, headers, body)
- Timestamp of the error
- Your API key prefix (e.g., `hg_v2_abc...`)