Code Examples
Practical examples to get you started with Content Hub API
List Content
JavaScriptconst response = await fetch('https://api.content-hub.net/v1/content', {
method: 'GET',
headers: {
'Authorization': 'Bearer your_api_key_here',
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log(data.items); // Array of content itemsCreate Content
Pythonimport requests
content_data = {
'title': 'My Article',
'content': 'Article content here',
'domain': 'example.com',
'slug': 'my-article'
}
response = requests.post(
'https://api.content-hub.net/v1/content',
json=content_data,
headers={'Authorization': 'Bearer your_api_key_here'}
)
result = response.json()
print(f"Created: {result['id']}")Error Handling
JavaScriptasync function createContent(contentData) {
try {
const response = await fetch('https://api.content-hub.net/v1/content', {
method: 'POST',
headers: {
'Authorization': 'Bearer your_api_key_here',
'Content-Type': 'application/json'
},
body: JSON.stringify(contentData)
});
if (!response.ok) {
if (response.status === 400) {
throw new Error('Invalid content data');
}
if (response.status === 429) {
throw new Error('Rate limit exceeded');
}
throw new Error(`API Error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Insurance check failed:', error.message);
throw error;
}
}Compliance Check
PHP<?php
$registration = 'AB12CDE';
$url = "https://api.cornucopia.net/v1/compliance/$registration";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'X-API-Key: your_api_key_here'
]
]);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true);
if ($data['compliant']) {
echo "Vehicle is compliant\n";
} else {
echo "Vehicle has compliance issues\n";
}
?>Web Application Integration
Complete example of integrating Cornucopia API into a vehicle rental web application.
Frontend (React)
import { useState } from 'react';
function VehicleCheck() {
const [registration, setRegistration] = useState('');
const [result, setResult] = useState(null);
const [loading, setLoading] = useState(false);
const checkInsurance = async () => {
setLoading(true);
try {
const response = await fetch('/api/check-insurance', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ registration })
});
const data = await response.json();
setResult(data);
} catch (error) {
setResult({ error: error.message });
}
setLoading(false);
};
return (
<div>
<input
value={registration}
onChange={(e) => setRegistration(e.target.value)}
placeholder="Enter registration (e.g., AB12CDE)"
/>
<button onClick={checkInsurance} disabled={loading}>
{loading ? 'Checking...' : 'Check Insurance'}
</button>
{result && (
<div>
{result.error ? (
<p className="error">{result.error}</p>
) : (
<div>
<p>Insured: {result.insured ? 'Yes' : 'No'}</p>
{result.policy && (
<div>
<p>Policy: {result.policy.number}</p>
<p>Valid until: {result.policy.validTo}</p>
</div>
)}
</div>
)}
</div>
)}
</div>
);
}Backend (Node.js/Express)
const express = require('express');
const router = express.Router();
router.post('/check-insurance', async (req, res) => {
const { registration } = req.body;
try {
const response = await fetch(`https://api.content-hub.net/v1/content/${registration}`, {
headers: {
'X-API-Key': process.env.CONTENT_HUB_API_KEY
}
});
if (!response.ok) {
throw new Error(`API responded with status: ${response.status}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Insurance check failed:', error);
res.status(500).json({ error: 'Failed to check insurance status' });
}
});
module.exports = router;Mobile App Integration
Example implementation for a React Native mobile application.
React Native Component
import React, { useState } from 'react';
import { View, Text, TextInput, Button, Alert } from 'react-native';
const InsuranceChecker = () => {
const [registration, setRegistration] = useState('');
const [loading, setLoading] = useState(false);
const checkInsurance = async () => {
setLoading(true);
try {
const response = await fetch('https://api.cornucopia.net/v1/vehicle/' + registration + '/insurance', {
headers: {
'X-API-Key': 'your_api_key_here'
}
});
const data = await response.json();
if (data.insured) {
Alert.alert('Insurance Status', 'Vehicle is insured and compliant');
} else {
Alert.alert('Insurance Status', 'Vehicle is not insured');
}
} catch (error) {
Alert.alert('Error', 'Failed to check insurance status');
}
setLoading(false);
};
return (
<View style={{ padding: 20 }}>
<TextInput
placeholder="Enter vehicle registration"
value={registration}
onChangeText={setRegistration}
style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
/>
<Button
title={loading ? "Checking..." : "Check Insurance"}
onPress={checkInsurance}
disabled={loading}
/>
</View>
);
};Swift (iOS)
import Foundation
class CornucopiaService {
private let apiKey = "your_api_key_here"
private let baseURL = "https://api.cornucopia.net/v1"
func checkInsurance(registration: String) async throws -> InsuranceStatus {
let url = URL(string: "(baseURL)/vehicle/(registration)/insurance")!
var request = URLRequest(url: url)
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw CornucopiaError.invalidResponse
}
let decoder = JSONDecoder()
return try decoder.decode(InsuranceStatus.self, from: data)
}
}
struct InsuranceStatus: Codable {
let registration: String
let insured: Bool
let policy: Policy?
}
struct Policy: Codable {
let number: String
let insurer: String
let validFrom: String
let validTo: String
}
enum CornucopiaError: Error {
case invalidResponse
}Batch Processing for Fleet Management
Process multiple vehicles efficiently for fleet operators.
Python Batch Processor
import asyncio
import aiohttp
import csv
from typing import List, Dict
class FleetInsuranceChecker:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.cornucopia.net/v1"
async def check_vehicles_batch(self, registrations: List[str]) -> List[Dict]:
"""Check insurance status for multiple vehicles"""
async with aiohttp.ClientSession() as session:
tasks = []
for reg in registrations:
task = self._check_single_vehicle(session, reg)
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
# Process results
processed_results = []
for i, result in enumerate(results):
if isinstance(result, Exception):
processed_results.append({
'registration': registrations[i],
'error': str(result)
})
else:
processed_results.append(result)
return processed_results
async def _check_single_vehicle(self, session: aiohttp.ClientSession, registration: str) -> Dict:
url = f"{self.base_url}/vehicle/{registration}/insurance"
headers = {'X-API-Key': self.api_key}
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
return {
'registration': registration,
'insured': data.get('insured', False),
'policy_number': data.get('policy', {}).get('number'),
'insurer': data.get('policy', {}).get('insurer')
}
else:
raise Exception(f"API error: {response.status}")
# Usage example
async def main():
checker = FleetInsuranceChecker("your_api_key_here")
# Load registrations from CSV
registrations = []
with open('fleet_vehicles.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
registrations.append(row['registration'])
results = await checker.check_vehicles_batch(registrations)
# Save results
with open('insurance_status.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['registration', 'insured', 'policy_number', 'insurer', 'error'])
writer.writeheader()
writer.writerows(results)
if __name__ == "__main__":
asyncio.run(main())Webhook Integration
Handle real-time updates via webhooks for compliance monitoring.
Express.js Webhook Handler
const express = require('express');
const crypto = require('crypto');
const router = express.Router();
// Webhook secret for verification (set in Content Hub dashboard)
const WEBHOOK_SECRET = process.env.CONTENT_HUB_WEBHOOK_SECRET;
router.post('/webhook/insurance-updates', express.raw({ type: 'application/json' }), (req, res) => {
// Verify webhook signature
const signature = req.headers['x-cornucopia-signature'];
const expectedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
return res.status(401).json({ error: 'Invalid signature' });
}
const event = JSON.parse(req.body);
console.log('Received webhook:', event.type);
switch (event.type) {
case 'insurance.expired':
handleInsuranceExpired(event.data);
break;
case 'vehicle.registered':
handleVehicleRegistered(event.data);
break;
case 'compliance.violation':
handleComplianceViolation(event.data);
break;
}
res.json({ received: true });
});
function handleInsuranceExpired(data) {
// Send notification to fleet manager
console.log(`Insurance expired for vehicle: ${data.registration}`);
// Update database, send alerts, etc.
}
function handleVehicleRegistered(data) {
// Process new vehicle registration
console.log(`New vehicle registered: ${data.registration}`);
}
function handleComplianceViolation(data) {
// Handle compliance issues
console.log(`Compliance violation: ${data.registration} - ${data.violation_type}`);
}
module.exports = router;Webhook Event Types
insurance.expired
Triggered when a vehicle's insurance policy expires
vehicle.registered
Triggered when a new vehicle is registered in the system
compliance.violation
Triggered when a vehicle violates compliance requirements
policy.updated
Triggered when insurance policy information is updated
Best Practices
- Always implement proper error handling and retry logic
- Cache results when appropriate to reduce API calls
- Use webhooks for real-time updates instead of polling
- Validate API responses before processing
- Implement rate limiting on your client side
- Store API keys securely and rotate them regularly