Error Handling
Learn how to handle and troubleshoot errors when using the Screenshot API.
Error Response Format
All API errors return a JSON object with an error field describing the issue. Some errors include additional fields for context.
Standard Error Format
{
"error":"Error message",
"details": [...], // Optional: Additional error details
"url":"...", // Optional: The URL that failed
"message":"..." // Optional: Technical details
}HTTP Status Codes
The API uses standard HTTP status codes to indicate success or failure:
2xx- Success4xx- Client errors (invalid request, authentication, etc.)5xx- Server errors (screenshot generation failed)
Error Codes Reference
Bad Request
The request is malformed or contains invalid parameters
Common Causes
- Missing required field (url)
- Invalid URL format
- Parameters out of allowed range
- Invalid enum value (format, device)
Solution
Check the API reference for valid parameter formats and constraints
Example Response
{
"error":"Invalid URL format",
"details": [
{
"code":"invalid_string",
"path": ["url"],
"message":"Invalid URL format"
}
]
}Unauthorized
Authentication failed due to missing or invalid API key
Common Causes
- Missing Authorization header
- Invalid API key format
- API key has been revoked
- API key does not exist
Solution
Verify your API key is correct and active in your dashboard
Example Response
{
"error":"Invalid API key"
}Payment Required
Your account has insufficient credits to complete the request
Common Causes
- Credit balance is zero or too low
- Screenshot requires more credits than available
Solution
Purchase more credits from the pricing page
Example Response
{
"error":"Insufficient credits",
"required": 2,
"available": 0
}Too Many Requests
You've exceeded the rate limit
Common Causes
- More than 100 requests in the past hour
Solution
Wait until the rate limit resets or upgrade your plan
Example Response
{
"error":"Rate limit exceeded",
"limit": 100,
"reset": 1704123600
}Internal Server Error
Screenshot generation failed
Common Causes
- Target website is unreachable
- Navigation timeout (site took too long to load)
- Target site returned HTTP error (404, 500, etc.)
- Browser launch failed
- Page rendering error
Solution
Check that the target URL is accessible and try again
Example Response
{
"error":"Screenshot generation failed",
"url":"https://example.com",
"message":"Navigation timeout exceeded"
}Handling Errors in Your Code
JavaScript / Node.js
async function captureScreenshot(url) {
try {
const response = await fetch('https://snappkit.com/api/screenshot', {
method:'POST',
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
},
body: JSON.stringify({ url })
});
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
console.error('Invalid request:', error.details);
break;
case 401:
console.error('Authentication failed:', error.error);
break;
case 402:
console.error('Insufficient credits:', error);
// Redirect user to purchase more credits
break;
case 429:
console.error('Rate limited. Reset at:', new Date(error.reset * 1000));
// Wait and retry
break;
case 500:
console.error('Screenshot failed:', error.message);
// Retry with exponential backoff
break;
}
throw new Error(error.error);
}
const blob = await response.blob();
return blob;
} catch (err) {
console.error('Request failed:', err);
throw err;
}
}Python
import requests
import time
def capture_screenshot(url):
try:
response = requests.post(
'https://snappkit.com/api/screenshot',
headers={
'Authorization': f'Bearer {os.environ["API_KEY"]}',
'Content-Type':'application/json'
},
json={'url': url}
)
if response.status_code == 400:
error = response.json()
print(f"Invalid request: {error['details']}")
raise ValueError(error['error'])
elif response.status_code == 401:
print("Authentication failed. Check your API key.")
raise PermissionError("Invalid API key")
elif response.status_code == 402:
error = response.json()
print(f"Insufficient credits: {error['required']} required, {error['available']} available")
raise Exception("Insufficient credits")
elif response.status_code == 429:
error = response.json()
reset_time = error['reset']
wait_seconds = reset_time - time.time()
print(f"Rate limited. Retry after {wait_seconds} seconds")
raise Exception("Rate limit exceeded")
elif response.status_code == 500:
error = response.json()
print(f"Screenshot failed: {error['message']}")
raise Exception(f"Server error: {error['error']}")
response.raise_for_status()
return response.content
except requests.RequestException as e:
print(f"Request failed: {e}")
raiseRetry Strategy
For 500 errors and 429 rate limit errors, implement exponential backoff:
async function captureWithRetry(url, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch('https://snappkit.com/api/screenshot', {
method:'POST',
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
},
body: JSON.stringify({ url })
});
if (response.ok) {
return await response.blob();
}
// Don't retry client errors (4xx except 429)
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
const error = await response.json();
throw new Error(error.error);
}
// Retry server errors (5xx) and rate limits (429)
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
console.log(`Retry attempt ${attempt} after ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
// Max retries exceeded
const error = await response.json();
throw new Error(`Failed after ${maxRetries} attempts: ${error.error}`);
} catch (err) {
if (attempt === maxRetries) throw err;
}
}
}Troubleshooting Common Issues
"Navigation timeout exceeded"
The target website took too long to load (30+ seconds). Try:
- Verify the URL is accessible in your browser
- Check if the site is experiencing downtime
- Add a
delayparameter for slow-loading sites - Try again later if the site is temporarily unavailable
"Invalid URL format"
The URL doesn't meet validation requirements. Ensure:
- URL starts with
http://orhttps:// - No typos or special characters
- Domain name is valid
"Target site returned 404"
The webpage doesn't exist. Verify the URL is correct and the page is publicly accessible.
Screenshots are blank or incomplete
The page may require JavaScript execution. Try:
- Adding a
delayof 2000-5000ms - Using
fullPage: truefor long pages