Code Examples
Ready-to-use code examples in multiple programming languages for integrating with the Weir AI API v1.0.1. These examples demonstrate common patterns and best practices for different use cases.JavaScript/Node.js
Modern JavaScript examples with async/await, fetch API, and error handling.
Python
Python examples with requests library, error handling, and best practices.
PHP
PHP examples with cURL, error handling, and modern PHP practices.
cURL
Command-line examples for testing, automation, and quick API calls.
Quick Start Examples
External API - Generate Access Token
const generateAccessToken = async (clientId, secretKey) => {
const credentials = btoa(`${clientId}:${secretKey}`);
try {
const response = await fetch('https://api.weir.ai/auth/token', {
method: 'POST',
headers: {
'Authorization': `Basic ${credentials}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.data.accessToken;
} catch (error) {
console.error('Error generating access token:', error);
throw error;
}
};
// Usage
const accessToken = await generateAccessToken('your_client_id', 'your_secret_key');
console.log('Access Token:', accessToken);
import requests
import base64
def generate_access_token(client_id, secret_key):
credentials = base64.b64encode(f"{client_id}:{secret_key}".encode()).decode()
try:
response = requests.post(
'https://api.weir.ai/auth/token',
headers={
'Authorization': f'Basic {credentials}',
'Content-Type': 'application/json'
}
)
response.raise_for_status()
data = response.json()
return data['data']['accessToken']
except requests.exceptions.RequestException as e:
print(f'Error generating access token: {e}')
raise
# Usage
access_token = generate_access_token('your_client_id', 'your_secret_key')
print(f'Access Token: {access_token}')
function generateAccessToken($clientId, $secretKey) {
$credentials = base64_encode($clientId . ':' . $secretKey);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weir.ai/auth/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Basic ' . $credentials,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("HTTP error: $httpCode");
}
$data = json_decode($response, true);
return $data['data']['accessToken'];
}
// Usage
try {
$accessToken = generateAccessToken('your_client_id', 'your_secret_key');
echo "Access Token: $accessToken";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
# Generate access token
curl -X POST 'https://api.weir.ai/auth/token' \
-H 'Content-Type: application/json' \
-u 'your_client_id:your_secret_key'
# Use the token for subsequent requests
curl -X GET 'https://api.weir.ai/external/endpoint' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-H 'Content-Type: application/json'
Console API - Create Team
const createTeam = async (accessToken, teamName) => {
try {
const response = await fetch('https://api.weir.ai/org/create/team', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'x-source': 'console'
},
body: JSON.stringify({ name: teamName })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.data;
} catch (error) {
console.error('Error creating team:', error);
throw error;
}
};
// Usage
const team = await createTeam('your_access_token', 'Development Team');
console.log('Created team:', team);
import requests
def create_team(access_token, team_name):
try:
response = requests.post(
'https://api.weir.ai/org/create/team',
headers={
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
'x-source': 'console'
},
json={'name': team_name}
)
response.raise_for_status()
data = response.json()
return data['data']
except requests.exceptions.RequestException as e:
print(f'Error creating team: {e}')
raise
# Usage
team = create_team('your_access_token', 'Development Team')
print(f'Created team: {team}')
function createTeam($accessToken, $teamName) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weir.ai/org/create/team');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json',
'x-source: console'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['name' => $teamName]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 201) {
throw new Exception("HTTP error: $httpCode");
}
$data = json_decode($response, true);
return $data['data'];
}
// Usage
try {
$team = createTeam('your_access_token', 'Development Team');
echo "Created team: " . json_encode($team);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
curl -X POST 'https://api.weir.ai/org/create/team' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-H 'x-source: console' \
-d '{
"name": "Development Team"
}'
Common Patterns
Token Management
class TokenManager {
constructor() {
this.accessToken = null;
this.refreshToken = null;
this.tokenExpiresAt = null;
}
async login(username, password) {
const response = await fetch('https://api.weir.ai/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
this.accessToken = data.data.accessToken;
this.refreshToken = data.data.refreshToken;
this.tokenExpiresAt = Date.now() + (data.data.expiresIn * 1000);
return data;
}
async refreshToken() {
const response = await fetch('https://api.weir.ai/auth/refresh/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken: this.refreshToken })
});
const data = await response.json();
this.accessToken = data.data.accessToken;
this.refreshToken = data.data.refreshToken;
this.tokenExpiresAt = Date.now() + (data.data.expiresIn * 1000);
return data;
}
async makeRequest(url, options = {}) {
if (this.tokenExpiresAt && Date.now() >= this.tokenExpiresAt - 300000) {
await this.refreshToken();
}
return fetch(url, {
...options,
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
'x-source': 'console',
...options.headers
}
});
}
}
import time
import requests
class TokenManager:
def __init__(self):
self.access_token = None
self.refresh_token = None
self.token_expires_at = None
def login(self, username, password):
response = requests.post(
'https://api.weir.ai/auth/login',
json={'username': username, 'password': password}
)
response.raise_for_status()
data = response.json()
self.access_token = data['data']['accessToken']
self.refresh_token = data['data']['refreshToken']
self.token_expires_at = time.time() + data['data']['expiresIn']
return data
def refresh_token(self):
response = requests.post(
'https://api.weir.ai/auth/refresh/token',
json={'refreshToken': self.refresh_token}
)
response.raise_for_status()
data = response.json()
self.access_token = data['data']['accessToken']
self.refresh_token = data['data']['refreshToken']
self.token_expires_at = time.time() + data['data']['expiresIn']
return data
def make_request(self, method, url, **kwargs):
if self.token_expires_at and time.time() >= self.token_expires_at - 300:
self.refresh_token()
headers = {
'Authorization': f'Bearer {self.access_token}',
'Content-Type': 'application/json',
'x-source': 'console'
}
headers.update(kwargs.get('headers', {}))
kwargs['headers'] = headers
return requests.request(method, url, **kwargs)
class TokenManager {
private $accessToken;
private $refreshToken;
private $tokenExpiresAt;
public function login($username, $password) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weir.ai/auth/login');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'username' => $username,
'password' => $password
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("HTTP error: $httpCode");
}
$data = json_decode($response, true);
$this->accessToken = $data['data']['accessToken'];
$this->refreshToken = $data['data']['refreshToken'];
$this->tokenExpiresAt = time() + $data['data']['expiresIn'];
return $data;
}
public function refreshToken() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weir.ai/auth/refresh/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'refreshToken' => $this->refreshToken
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("HTTP error: $httpCode");
}
$data = json_decode($response, true);
$this->accessToken = $data['data']['accessToken'];
$this->refreshToken = $data['data']['refreshToken'];
$this->tokenExpiresAt = time() + $data['data']['expiresIn'];
return $data;
}
public function makeRequest($method, $url, $data = null) {
if ($this->tokenExpiresAt && time() >= $this->tokenExpiresAt - 300) {
$this->refreshToken();
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->accessToken,
'Content-Type: application/json',
'x-source: console'
]);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception("HTTP error: $httpCode");
}
return json_decode($response, true);
}
}
Error Handling
class APIError extends Error {
constructor(message, code, details, status) {
super(message);
this.name = 'APIError';
this.code = code;
this.details = details;
this.status = status;
}
}
async function makeAPIRequest(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json();
throw new APIError(
errorData.error?.message || 'API request failed',
errorData.error?.code || 'UNKNOWN_ERROR',
errorData.error?.details,
response.status
);
}
return await response.json();
} catch (error) {
if (error instanceof APIError) {
throw error;
}
// Handle network errors
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new APIError(
'Network error: Unable to connect to API',
'NETWORK_ERROR',
null,
0
);
}
throw new APIError(
'Unexpected error occurred',
'UNEXPECTED_ERROR',
error.message,
0
);
}
}
class APIError(Exception):
def __init__(self, message, code, details=None, status=None):
super().__init__(message)
self.code = code
self.details = details
self.status = status
def make_api_request(method, url, **kwargs):
try:
response = requests.request(method, url, **kwargs)
if not response.ok:
try:
error_data = response.json()
raise APIError(
error_data.get('error', {}).get('message', 'API request failed'),
error_data.get('error', {}).get('code', 'UNKNOWN_ERROR'),
error_data.get('error', {}).get('details'),
response.status_code
)
except ValueError:
raise APIError(
f'HTTP {response.status_code}: {response.text}',
'HTTP_ERROR',
None,
response.status_code
)
return response.json()
except requests.exceptions.RequestException as e:
raise APIError(
f'Network error: {str(e)}',
'NETWORK_ERROR',
None,
0
)
except Exception as e:
raise APIError(
f'Unexpected error: {str(e)}',
'UNEXPECTED_ERROR',
None,
0
)
class APIError extends Exception {
public $code;
public $details;
public $status;
public function __construct($message, $code, $details = null, $status = null) {
parent::__construct($message);
$this->code = $code;
$this->details = $details;
$this->status = $status;
}
}
function makeAPIRequest($method, $url, $data = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
$errorData = json_decode($response, true);
throw new APIError(
$errorData['error']['message'] ?? 'API request failed',
$errorData['error']['code'] ?? 'UNKNOWN_ERROR',
$errorData['error']['details'] ?? null,
$httpCode
);
}
return json_decode($response, true);
}
Language-Specific Examples
JavaScript/Node.js
- Modern ES6+ syntax with async/await
- Fetch API and error handling
- Token management and automatic refresh
- Complete integration examples
Python
- Requests library with error handling
- Token management and automatic refresh
- Complete integration examples
- Best practices and patterns
PHP
- cURL with error handling
- Token management and automatic refresh
- Complete integration examples
- Modern PHP practices
cURL
- Command-line examples
- Testing and automation scripts
- Authentication examples
- Complete endpoint examples
Best Practices
Authentication
Authentication
- Store credentials securely in environment variables
- Implement automatic token refresh
- Handle authentication errors gracefully
- Use different credentials for different environments
Error Handling
Error Handling
- Implement comprehensive error handling
- Provide clear error messages to users
- Log errors for debugging
- Handle network failures gracefully
Performance
Performance
- Cache responses when possible
- Use pagination for large datasets
- Implement retry logic with backoff
- Monitor rate limit headers
Security
Security
- Always use HTTPS
- Validate and sanitize input
- Implement proper CORS policies
- Follow OWASP security guidelines
Getting Started
Choose Your Language
Select the programming language that best fits your project.
Review Examples
Browse the examples for your chosen language and use case.
Copy and Customize
Copy the relevant examples and customize them for your needs.
Test and Iterate
Test your implementation and iterate based on your requirements.
Pro Tip: Start with the basic examples to understand the API patterns, then use the more complex examples for building complete integrations. All examples include error handling and best practices.