Se rendre au contenu

Exemples de code API

API et intégrations OdooBot 70 vues
Exemples de code pour utiliser l'API VedTech en Python, JavaScript, PHP et cURL.

Exemples de code API

Exemples de code prets a l'emploi pour integrer l'API VedTech dans differents langages de programmation.

Python

import requests

API_KEY = "your_api_key_here"
BASE_URL = "https://vedtechsolutions.com/api/v1"

headers = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

# Get all instances usage
response = requests.get(f"{BASE_URL}/usage/instances", headers=headers)
data = response.json()

if data["success"]:
    for instance in data["data"]["instances"]:
        print(f"{instance['name']}: CPU {instance['usage']['cpu_percent']}%")
else:
    print(f"Error: {data['error']['message']}")

Python avec gestion des erreurs

import requests
from requests.exceptions import RequestException

class VedTechAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://vedtechsolutions.com/api/v1"
        self.session = requests.Session()
        self.session.headers.update({
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        })

    def get_instance_usage(self, instance_id):
        try:
            response = self.session.get(
                f"{self.base_url}/usage/instance/{instance_id}"
            )
            response.raise_for_status()
            return response.json()
        except RequestException as e:
            return {"success": False, "error": str(e)}

# Usage
api = VedTechAPI("your_api_key")
usage = api.get_instance_usage(91)
print(usage)

JavaScript (Node.js)

const axios = require('axios');

const API_KEY = 'your_api_key_here';
const BASE_URL = 'https://vedtechsolutions.com/api/v1';

const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    'X-API-Key': API_KEY,
    'Content-Type': 'application/json'
  }
});

// Get instance usage
async function getInstanceUsage(instanceId) {
  try {
    const response = await api.get(`/usage/instance/${instanceId}`);
    return response.data;
  } catch (error) {
    console.error('API Error:', error.response?.data || error.message);
    throw error;
  }
}

// Usage
getInstanceUsage(91).then(data => {
  console.log('CPU Usage:', data.data.current_usage.cpu_percent + '%');
});

JavaScript (Navigateur/Fetch)

const API_KEY = 'your_api_key_here';

async function fetchInstances() {
  const response = await fetch(
    'https://vedtechsolutions.com/api/v1/usage/instances',
    {
      headers: {
        'X-API-Key': API_KEY
      }
    }
  );

  const data = await response.json();

  if (data.success) {
    data.data.instances.forEach(instance => {
      console.log(`${instance.name}: ${instance.usage.cpu_percent}% CPU`);
    });
  }
}

fetchInstances();

PHP

<?php
$api_key = 'your_api_key_here';
$base_url = 'https://vedtechsolutions.com/api/v1';

function apiRequest($endpoint, $api_key) {
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => "https://vedtechsolutions.com/api/v1" . $endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "X-API-Key: " . $api_key,
            "Content-Type: application/json"
        ]
    ]);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        return ['success' => false, 'error' => $error];
    }

    return json_decode($response, true);
}

// Get all instances
$result = apiRequest('/usage/instances', $api_key);

if ($result['success']) {
    foreach ($result['data']['instances'] as $instance) {
        echo $instance['name'] . ': ' . $instance['usage']['cpu_percent'] . "% CPU\n";
    }
}
?>

cURL (Ligne de commande)

# Get all instances
curl -X GET "https://vedtechsolutions.com/api/v1/usage/instances" \
  -H "X-API-Key: your_api_key_here" | jq

# Get specific instance
curl -X GET "https://vedtechsolutions.com/api/v1/usage/instance/91" \
  -H "X-API-Key: your_api_key_here" | jq

# Get usage history (last 7 days)
curl -X GET "https://vedtechsolutions.com/api/v1/usage/instance/91/history?period=7d" \
  -H "X-API-Key: your_api_key_here" | jq

# Pretty print with jq filtering
curl -s -X GET "https://vedtechsolutions.com/api/v1/usage/instances" \
  -H "X-API-Key: your_api_key_here" | \
  jq '.data.instances[] | {name, cpu: .usage.cpu_percent, ram: .usage.ram_percent}'

Exemple d'integration Webhook

Configurez des alertes de surveillance en utilisant l'API avec un simple script de sondage :

#!/bin/bash
# Simple monitoring script - run via cron

API_KEY="your_api_key_here"
THRESHOLD=80
WEBHOOK_URL="https://hooks.slack.com/your-webhook"

# Get usage data
USAGE=$(curl -s "https://vedtechsolutions.com/api/v1/usage/instances" \
  -H "X-API-Key: $API_KEY")

# Check each instance
echo "$USAGE" | jq -r '.data.instances[] | "\(.name),\(.usage.cpu_percent)"' | \
while IFS=',' read -r name cpu; do
  if (( $(echo "$cpu > $THRESHOLD" | bc -l) )); then
    # Send alert to Slack
    curl -X POST "$WEBHOOK_URL" \
      -H "Content-Type: application/json" \
      -d "{\"text\":\"High CPU Alert: $name at ${cpu}%\"}"
  fi
done

Besoin d'aide ?

Si vous avez besoin d'assistance pour l'integration de l'API, creez un ticket de support avec les details de votre cas d'utilisation.

Cet article vous a-t-il été utile ?
Rechercher des articles
Encore besoin d'aide ?

Notre équipe de support est prête à vous assister.

Créer un ticket
Aller au contenu principal
Discutez avec nous