Error Handling & Response Codes
The Product Classifier API uses HTTP status codes and structured JSON responses to communicate request outcomes. Understanding both successful responses and error conditions helps you build robust integrations that handle all scenarios gracefully.
HTTP Status Codes
The API returns standard HTTP status codes to indicate the outcome of your request:
200 OK - Successful Response
The request was processed successfully and returns a JSON response. This doesn’t necessarily mean a category was found—check the categoryFound field in the response to determine that.
The JSON response includes fields like success, categoryFound, categoryId, categoryPath, confidenceLevel, and more. For complete details on the response structure and all available fields, see Making API Requests.
400 Bad Request
The request is malformed or missing required parameters. Common causes:
- Missing the required
productparameter - Invalid parameter types (e.g., sending a string where a boolean is expected)
- Invalid taxonomy value (must be
"Shopify"or"Google")
Response format: Plain text error message
Example error response:
Bad JSON format.How to fix: Validate your request payload before sending. Ensure the product parameter is present and all optional parameters use the correct data types.
401 Unauthorized
Authentication failed. This occurs when:
- No API key is provided in the Authorization header
- The API key is invalid or malformed
- The API key has been deleted
Response format: Plain text error message
Example error response:
Cannot find account for this API key.How to fix: Verify your API key is correct and included in the Authorization header as a Bearer token. If the key was deleted, generate a new one from your dashboard. See Managing API Keys for details.
403 Forbidden
Your account has insufficient credits to process the request. This occurs when both your monthly credits and any top-up credits have been exhausted.
Response format: Plain text error message
Example error response:
Insufficient credits.How to fix: Purchase top-up credits or upgrade to a plan with a higher monthly credit allocation. You can also wait for your next billing cycle when monthly credits renew. See Understanding Credits and Auto Recharge Setup for details.
413 Request Entity Too Large
The request payload exceeds the maximum allowed size. This typically occurs when the product description is excessively long.
Response format: Plain text error message
Example error response:
Request entity too large.How to fix: Reduce the size of your product description. While Product Classifier can handle detailed descriptions, excessively long text (typically over several thousand characters) may exceed payload limits. Focus on the most relevant product details rather than including exhaustive information.
429 Too Many Requests
You’ve exceeded your rate limit. This can occur at two levels:
- Product Classifier API rate limits - Request volume to our service
- Upstream AI service rate limits - Capacity from the AI models we use
Response format: Plain text error message
Example error response:
Rate limit exceeded.How to fix: Implement exponential backoff in your retry logic. Most 429 responses include a Retry-After header indicating when to retry. The request is not processed and no credit is deducted when you receive this error. See Rate Limits & Usage Quotas for details on default limits and how to request increases.
Example retry logic:
async function classifyWithRetry(product, maxRetries = 3) {
let retryDelay = 1000; // Start with 1 second
for (let i = 0; i < maxRetries; i++) {
const response = await fetch('https://api.productclassifier.com/api/v1/products/categorize', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({ product })
});
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
const delay = retryAfter ? parseInt(retryAfter) * 1000 : retryDelay;
await new Promise(resolve => setTimeout(resolve, delay));
retryDelay *= 2; // Exponential backoff
continue;
}
return response.json();
}
throw new Error('Max retries exceeded');
}500 Internal Server Error
An unexpected error occurred on the server. This is rare but can happen due to:
- Temporary service disruption
- Upstream AI service issues
- Infrastructure problems
Response format: Plain text error message
Example error response:
An internal server error occurred. Please try again later.How to fix: Retry the request after a brief delay. If the problem persists, contact support at support@productclassifier.com with the timestamp and request details.
Handling Errors in Your Application
Recommended Error Handling Pattern
async function classifyProduct(product, options = {}) {
try {
const response = await fetch('https://api.productclassifier.com/api/v1/products/categorize', {
method: 'POST',
headers: {
'Authorization': `Bearer ${YOUR_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
product,
taxonomy: options.taxonomy || 'Google',
customInstructionsForAi: options.customInstructions || null,
leafsOnly: options.leafsOnly || false,
fallbackToBestGuess: options.fallbackToBestGuess || false
})
});
// Non-200 responses return plain text error messages
if (response.status !== 200) {
const errorText = await response.text();
throw new Error(`API error (${response.status}): ${errorText}`);
}
const data = await response.json();
// Handle classification errors
if (!data.success) {
throw new Error(`Classification error: ${data.error}`);
}
// Handle successful classification
if (data.categoryFound) {
return {
category: data.categoryId,
path: data.categoryPath,
confidence: data.confidenceLevel,
needsReview: data.confidenceLevel === 'RelevantCategory'
};
} else {
// No category found
return {
category: null,
path: null,
confidence: 'None',
needsReview: true
};
}
} catch (error) {
console.error('Classification failed:', error.message);
throw error;
}
}Error Recovery Strategies
For 401 Unauthorized:
- Verify API key is correct
- Check if key has been deleted
- Generate a new key if necessary
For 403 Forbidden:
- Check credit balance in dashboard
- Purchase top-up credits
- Set up auto-recharge to prevent future interruptions
- Upgrade plan for higher monthly allocation
For 413 Request Entity Too Large:
- Reduce the length of your product description
- Focus on the most relevant product details
- Remove unnecessary or redundant information
For 429 Rate Limit:
- Implement exponential backoff
- Respect Retry-After header if provided
- Consider requesting higher rate limits for your account
- Batch requests during off-peak hours
For 500 Server Error:
- Retry after a brief delay
- Implement exponential backoff
- Contact support if problem persists
For categoryFound: false:
- Improve product description with more details
- Enable
fallbackToBestGuessfor coverage - Add custom instructions for recurring patterns
- Manual classification if description cannot be improved
Monitoring and Logging
Track these metrics to identify patterns and issues:
Response distribution:
- Percentage of
confidenceLevel: "AI"(target: high) - Percentage of
confidenceLevel: "RelevantCategory"(review these) - Percentage of
categoryFound: false(investigate these)
Error rates:
- 429 errors (indicates rate limit issues)
- 403 errors (indicates credit exhaustion)
- 401 errors (indicates authentication issues)
- 500 errors (indicates service issues)
Response times:
- Average classification time
- Slowest classifications
- Timeout rates
Use this data to optimize your integration, improve product descriptions, and plan capacity needs.
Testing Error Scenarios
Test your error handling with these scenarios:
Invalid API key:
curl -X POST https://api.productclassifier.com/api/v1/products/categorize \
-H "Authorization: Bearer invalid_key_here" \
-H "Content-Type: application/json" \
-d '{"product": "Test product"}'Missing required parameter:
curl -X POST https://api.productclassifier.com/api/v1/products/categorize \
-H "Authorization: Bearer your_api_key_here" \
-H "Content-Type: application/json" \
-d '{}'Invalid taxonomy value:
curl -X POST https://api.productclassifier.com/api/v1/products/categorize \
-H "Authorization: Bearer your_api_key_here" \
-H "Content-Type: application/json" \
- '{"product": "Test product", "taxonomy": "InvalidTaxonomy"}'