Sample API Code
This Python example demonstrates LogZilla API integration with comprehensive error handling, authentication, and query management. The code sample provides practical implementations for common API operations.
Prerequisites
- Python 3.6 or higher
- requests library
import requests
import json
import time
## Configuration
# Replace with actual LogZilla API URL and authentication token.
BASE_URL = "https://your-logzilla-server/api"
AUTH_TOKEN = "your-api-token-here"
HEADERS = {
"Authorization": f"token {AUTH_TOKEN}",
"Content-Type": "application/json"
}
## API Request Function
def make_api_request(url, method="GET", payload=None):
"""
Reusable function to make API requests with comprehensive error handling.
"""
try:
if method == "GET":
response = requests.get(url, headers=HEADERS, timeout=10)
elif method == "POST":
# Apply timeout for consistency
response = requests.post(url, json=payload, headers=HEADERS, timeout=10)
else:
# Unsupported method
raise ValueError(f"Unsupported HTTP method: {method}")
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("API Error: 401 Unauthorized. Token refresh required.")
elif e.response.status_code == 429:
print("API Error: 429 Too Many Requests. Waiting 60 seconds...")
time.sleep(60)
elif e.response.status_code == 404:
print(f"API Error: 404 Not Found at {url}")
return None
else:
print(f"API Error: {e.response.json().get('detail', str(e))}")
raise
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
raise
## Usage Example
EVENT_ID = "your-event-id-here"
event_url = f"{BASE_URL}/events/{EVENT_ID}"
try:
print(f"Retrieving event with ID: {EVENT_ID}")
event_data = make_api_request(event_url, method="GET")
if event_data is not None:
print("Retrieved event data:")
print(json.dumps(event_data, indent=2))
else:
print("Event not found.")
except ValueError as e:
print(f"Request configuration error: {e}")
except requests.exceptions.RequestException:
print("Request failed. Check error messages for details.")