Making API Requests
Learn how to structure requests, handle parameters, and process responses effectively.
HTTP Methods
APIVerve primarily uses GET and POST requests depending on the endpoint:
GET Requests
Used for data retrieval operations. Parameters are sent as query strings in the URL. Most APIVerve endpoints use GET requests for fetching data like weather information, stock prices, or validation results.
GET /v1/weather?city=London&units=metric HTTP/1.1
Host: api.apiverve.com
X-API-Key: your_api_key_here
POST Requests
Used for data processing operations that require complex input or file uploads. Parameters are sent in the request body as JSON. Examples include PDF generation, image processing, or data transformation services.
POST /v1/htmltopdf HTTP/1.1
Host: api.apiverve.com
X-API-Key: your_api_key_here
Content-Type: application/json
{
"html": "<h1>Hello World</h1>",
"options": {
"format": "A4"
}
}
Required Headers
All requests must include these headers:
X-API-Key: your_api_key_here
Content-Type: application/json
User-Agent: YourApp/1.0 (optional but recommended)
While optional, including a descriptive User-Agent helps us provide better support and analytics.
GET Requests
Most APIVerve endpoints use GET requests with query parameters:
curl -X GET \
"https://api.apiverve.com/v1/weather?city=London&units=metric" \
-H "X-API-Key: your_api_key_here"
const params = new URLSearchParams({
city: 'London',
units: 'metric'
});
const response = await fetch(`https://api.apiverve.com/v1/weather?${params}`, {
method: 'GET',
headers: {
'X-API-Key': 'your_api_key_here'
}
});
const data = await response.json();
console.log(data);
import requests
params = {
'city': 'London',
'units': 'metric'
}
response = requests.get(
'https://api.apiverve.com/v1/weather',
params=params,
headers={'X-API-Key': 'your_api_key_here'}
)
data = response.json()
print(data)
POST Requests
Some endpoints require POST requests, typically for processing operations:
curl -X POST \
"https://api.apiverve.com/v1/htmltopdf" \
-H "X-API-Key: your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"html": "<h1>Hello World</h1>",
"options": {
"format": "A4",
"orientation": "portrait"
}
}'
const requestBody = {
html: '<h1>Hello World</h1>',
options: {
format: 'A4',
orientation: 'portrait'
}
};
const response = await fetch('https://api.apiverve.com/v1/htmltopdf', {
method: 'POST',
headers: {
'X-API-Key': 'your_api_key_here',
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
const data = await response.json();
console.log(data);
import requests
import json
payload = {
'html': '<h1>Hello World</h1>',
'options': {
'format': 'A4',
'orientation': 'portrait'
}
}
response = requests.post(
'https://api.apiverve.com/v1/htmltopdf',
headers={
'X-API-Key': 'your_api_key_here',
'Content-Type': 'application/json'
},
json=payload
)
data = response.json()
print(data)
Response Formats
APIVerve APIs support multiple response formats. You can specify the desired format using the Accept header:
curl "https://api.apiverve.com/v1/weather?city=London" \
-H "X-API-Key: your_api_key_here" \
-H "Accept: application/json"
# JSON is the default format, so Accept header is optional
curl "https://api.apiverve.com/v1/weather?city=London" \
-H "X-API-Key: your_api_key_here"
curl "https://api.apiverve.com/v1/weather?city=London" \
-H "X-API-Key: your_api_key_here" \
-H "Accept: application/xml"
# Alternative: using format query parameter
curl "https://api.apiverve.com/v1/weather?city=London&format=xml" \
-H "X-API-Key: your_api_key_here"
curl "https://api.apiverve.com/v1/weather?city=London" \
-H "X-API-Key: your_api_key_here" \
-H "Accept: application/yaml"
# Alternative: using format query parameter
curl "https://api.apiverve.com/v1/weather?city=London&format=yaml" \
-H "X-API-Key: your_api_key_here"
You can specify the response format using either a query parameter (?format=xml
) or the Accept header (Accept: application/xml
). The query parameter takes precedence if both are provided.
Error Handling
Always implement proper error handling to manage API failures gracefully:
async function makeApiRequest(endpoint, params) {
try {
const response = await fetch(`https://api.apiverve.com/v1/${endpoint}?${new URLSearchParams(params)}`, {
headers: {
'X-API-Key': process.env.APIVERVE_API_KEY
}
});
const data = await response.json();
if (data.status === 'error') {
throw new Error(`API Error: ${data.error}`);
}
return data.data;
} catch (error) {
console.error('Request failed:', error.message);
throw error;
}
}
import requests
import os
def make_api_request(endpoint, params=None):
try:
response = requests.get(
f'https://api.apiverve.com/v1/{endpoint}',
params=params or {},
headers={'X-API-Key': os.getenv('APIVERVE_API_KEY')},
timeout=30
)
response.raise_for_status() # Raises HTTPError for bad responses
data = response.json()
if data.get('status') == 'error':
raise Exception(f"API Error: {data.get('error')}")
return data.get('data')
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
raise
except Exception as e:
print(f"Error processing response: {e}")
raise
Best Practices
Set Reasonable Timeouts
Always configure timeouts for your API requests to prevent your application from hanging indefinitely. A timeout of 30-60 seconds is generally appropriate for most APIVerve endpoints. This ensures your application remains responsive even when network conditions are poor or the API is experiencing delays.
Implement Retry Logic
Network requests can fail for various reasons including temporary connectivity issues, server overload, or rate limiting. Implement exponential backoff retry logic to automatically retry failed requests with increasing delays between attempts. This is especially important when dealing with rate limits (429 status codes).
Cache API Responses
Reduce costs and improve performance by caching API responses when appropriate. Consider the nature of your data - static reference data can be cached for hours or days, while dynamic data may only be suitable for short-term caching. Always respect cache headers returned by the API and implement cache invalidation strategies.
Validate and Sanitize Input
Always validate and sanitize input parameters before sending them to the API. This prevents errors, reduces unnecessary API calls, and protects against potential security issues. Validate data types, required fields, format constraints, and acceptable value ranges before making requests.
Use Environment Variables
Store your API keys and other configuration values in environment variables rather than hardcoding them in your source code. This improves security, makes it easier to manage different environments (development, staging, production), and prevents accidental exposure of credentials in version control.
Monitor API Usage
Keep track of your API usage patterns, response times, and error rates. This helps you optimize your integration, identify issues early, and plan for scaling. Consider implementing logging and monitoring for successful requests, failed requests, and rate limit warnings.
Handling Rate Limits
Implement exponential backoff when you receive rate limit errors:
async function requestWithBackoff(url, options, maxRetries = 3) {
for (let attempt = 0; 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;
}
return response;
} catch (error) {
if (attempt === maxRetries) throw error;
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
}
}
}
Was this page helpful?
Help us improve our documentation