ContentClientApiModule
Supported versions
Supported Cortex XSOAR versions: 6.8.0 and later.
ContentClient API Module#
ContentClient is a drop-in replacement for BaseClient that provides enhanced reliability, observability, and developer experience features. It is designed to be fully backward compatible while offering powerful new capabilities for robust API integrations.
Table of Contents#
- Key Features
- Installation
- Quick Start
- Migration from BaseClient
- Authentication Handlers
- Resilience Policies
- Timeout Configuration
- Error Handling
- Metrics & Diagnostics
- State Management
- Complete Integration Example
- API Reference
Key Features#
| Feature | Description |
|---|---|
| Drop-in Replacement | Fully compatible with BaseClient constructor and _http_request method |
| Advanced Authentication | Built-in handlers for API Key, Bearer Token, Basic Auth, and OAuth2 (with auto-refresh) |
| Retry Policy | Configurable exponential backoff with jitter for transient failures |
| Rate Limiting | Token bucket algorithm to respect API rate limits |
| Circuit Breaker | Prevents cascading failures by temporarily blocking requests |
| Observability | Detailed execution metrics, structured logging, and diagnostic reports |
| Async Core | Built on httpx and anyio for high-performance async I/O |
Installation#
Import the module in your integration:
Quick Start#
Minimal Example#
Using HTTP Verb Helpers#
Migration from BaseClient#
Migrating from BaseClient to ContentClient requires zero code changes for basic usage. Simply replace the import and class name:
Before (BaseClient)#
After (ContentClient - Zero Changes)#
After (ContentClient - With Enhanced Auth)#
Once migrated, you can optionally adopt enhanced features like built-in auth handlers:
Gradual Enhancement#
You can adopt enhanced features incrementally:
Authentication Handlers#
API Key Authentication#
Add an API key to request headers or query parameters:
Bearer Token Authentication#
Add a Bearer token to the Authorization header:
Basic Authentication#
Use HTTP Basic Authentication:
OAuth2 Client Credentials#
Automatically handle OAuth2 token acquisition and refresh:
Custom Authentication Handler#
Create your own authentication handler for custom auth schemes:
Resilience Policies#
Retry Policy#
Configure automatic retries with exponential backoff:
Retryable Status Codes#
By default, the following HTTP status codes trigger a retry:
| Code | Description |
|---|---|
| 408 | Request Timeout |
| 413 | Payload Too Large |
| 425 | Too Early |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
| 502 | Bad Gateway |
| 503 | Service Unavailable |
| 504 | Gateway Timeout |
Retryable Exceptions#
The following network exceptions trigger a retry:
httpx.ConnectError- Connection failedhttpx.ReadTimeout- Read operation timed outhttpx.WriteTimeout- Write operation timed outhttpx.RemoteProtocolError- Protocol error from serverhttpx.PoolTimeout- Connection pool exhausted
Rate Limiting#
Prevent hitting API rate limits using the token bucket algorithm:
How Token Bucket Works#
- The bucket starts with
bursttokens - Tokens are added at
rate_per_secondrate - Each request consumes 1 token
- If no tokens available, the request waits until a token is available
- Maximum tokens in bucket is capped at
burst
Circuit Breaker#
Prevent cascading failures by temporarily blocking requests after repeated failures:
Circuit Breaker States#
| State | Description |
|---|---|
| Closed | Normal operation, requests are allowed |
| Open | Requests are blocked, raises ContentClientCircuitOpenError |
| Half-Open | After recovery timeout, one request is allowed to test the service |
Combining Policies#
Use all resilience policies together for maximum reliability:
Timeout Configuration#
Configure request timeout settings:
TimeoutSettings (Advanced)#
For advanced use cases, the TimeoutSettings class provides granular control over different timeout phases. This is primarily used internally but can be useful for understanding timeout behavior:
Note: The
timeoutparameter inContentClientconstructor accepts afloatvalue representing seconds. TheTimeoutSettingsclass is used internally for advanced timeout management.
Error Handling#
Exception Hierarchy#
Handling Errors#
Error Diagnosis#
Use the built-in error diagnosis helper:
Accessing Response Details#
Error objects include the original response when available:
Metrics & Diagnostics#
Execution Metrics#
Track request statistics automatically:
Diagnostic Mode#
Enable detailed request tracing for troubleshooting:
Health Check#
Perform a health check on the client:
Structured Logging#
The client provides structured logging with context:
State Management#
ContentClientState#
Manage pagination and collection state for resumable operations:
ContentClientContextStore#
Persist state to Demisto integration context:
Resumable Collection Example#
๐ง Complete Integration Example#
Here's a complete example of a production-ready integration:
API Reference#
ContentClient#
The main client class that extends BaseClient functionality.
Constructor Parameters#
| Parameter | Type | Default | Description |
|---|---|---|---|
base_url | str | Required | Base URL for the API |
verify | bool | True | Verify SSL certificates |
proxy | bool | False | Use system proxy settings |
ok_codes | tuple | () | HTTP status codes to consider successful (empty tuple means use standard HTTP success codes) |
headers | Dict[str, str] | None | Default headers for all requests |
auth | tuple | None | Basic auth credentials (username, password) |
timeout | float | 60.0 | Request timeout in seconds |
auth_handler | AuthHandler | None | Authentication handler instance |
retry_policy | RetryPolicy | None | Retry policy configuration |
rate_limiter | RateLimitPolicy | None | Rate limiting configuration |
circuit_breaker | CircuitBreakerPolicy | None | Circuit breaker configuration |
diagnostic_mode | bool | False | Enable detailed request tracing |
client_name | str | "ContentClient" | Client identifier for logging |
Methods#
| Method | Description |
|---|---|
_http_request(...) | Make an HTTP request (BaseClient compatible) |
get(url_suffix, ...) | Make a GET request |
post(url_suffix, ...) | Make a POST request |
put(url_suffix, ...) | Make a PUT request |
patch(url_suffix, ...) | Make a PATCH request |
delete(url_suffix, ...) | Make a DELETE request |
get_diagnostic_report() | Get comprehensive diagnostic report |
diagnose_error(error) | Get diagnosis and solution for an error |
health_check() | Check client health status |
close() | Close the client and release resources |
RetryPolicy#
Configuration for automatic request retries.
| Parameter | Type | Default | Description |
|---|---|---|---|
max_attempts | int | 5 | Maximum number of retry attempts |
initial_delay | float | 1.0 | Initial delay between retries (seconds) |
multiplier | float | 2.0 | Delay multiplier for exponential backoff |
max_delay | float | 60.0 | Maximum delay between retries (seconds) |
jitter | float | 0.2 | Random jitter factor (0.0 to 1.0) |
respect_retry_after | bool | True | Honor Retry-After header from server |
RateLimitPolicy#
Configuration for request rate limiting.
| Parameter | Type | Default | Description |
|---|---|---|---|
rate_per_second | float | 0.0 | Requests per second (0 = disabled) |
burst | int | 1 | Maximum burst capacity |
respect_retry_after | bool | True | Honor Retry-After header from server |
CircuitBreakerPolicy#
Configuration for circuit breaker pattern.
| Parameter | Type | Default | Description |
|---|---|---|---|
failure_threshold | int | 5 | Failures before opening circuit |
recovery_timeout | float | 60.0 | Seconds before attempting recovery |
TimeoutSettings#
Granular timeout configuration.
| Parameter | Type | Default | Description |
|---|---|---|---|
connect | float | 10.0 | Connection timeout (seconds) |
read | float | 60.0 | Read timeout (seconds) |
write | float | 60.0 | Write timeout (seconds) |
pool | float | 60.0 | Connection pool timeout (seconds) |
execution | float | None | Total execution timeout (seconds) |
safety_buffer | float | 30.0 | Buffer before execution timeout |
Authentication Handlers#
| Handler | Parameters |
|---|---|
APIKeyAuthHandler | key, header_name, query_param |
BearerTokenAuthHandler | token |
BasicAuthHandler | username, password |
OAuth2ClientCredentialsHandler | token_url, client_id, client_secret, scope, audience, auth_params, context_store |
Exceptions#
| Exception | Description |
|---|---|
ContentClientError | Base exception for all client errors |
ContentClientAuthenticationError | Authentication failed (401, 403) |
ContentClientRateLimitError | Rate limit exceeded (429) |
ContentClientTimeoutError | Execution timeout exceeded |
ContentClientCircuitOpenError | Circuit breaker is open |
ContentClientRetryError | All retry attempts exhausted |
ContentClientConfigurationError | Invalid configuration |