Général:FAQ API MAJ

De WikiFr_dbSQWare
Aller à la navigation Aller à la recherche
La version imprimable n’est plus prise en charge et peut comporter des erreurs de génération. Veuillez mettre à jour les signets de votre navigateur et utiliser à la place la fonction d’impression par défaut de celui-ci.

Généralités

Limites de cette section

Cette section n’a pas la prétention de traiter tous les cas possibles d'utilisation de l'API de mise à jour du référentiel.
Vous devez être à l'aise avec le concept des API et la gestion de token, si ce n'est pas le cas, faites appel au support.
Attention, vous allez mettre à jour la table du référentiel général, insert et/ou update, vous devez savoir ce que vous faites !

Paramétrage préalable

Afin de pouvoir utiliser l'API "update", vous devez au préalable avoir paramétré un login avec le type d'authentification "internal_api_update".

Exemples d'utilisation

Vous devez adapter les exemples suivants avec vos propres données (URL, user, password, ...)
Ceci représente une base pour du Python, PHP et shell.
Vous pouvez bien évidemment utiliser le langage de votre choix.

Python

import requests
import json

bearerToken = ""

"""
Does API request.

:param method  : Request method
:param url     : Website url
:param headers : JSON object headers 
:param data    : JSON object data
:return        : API request return
"""
def apiRequest(method, url, headers = {}, data = {}):
    response = requests.request(method, url, headers=headers, data=data)
    return response  

"""
Get bearer token.

:param username : Account username
:param password : Account password
:return         : Bearer token
"""
def getBearerToken(username, password):
    # Init request
    method  = 'POST'
    url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate_login.php"
    headers = {'Content-Type': 'application/json'}
    data    = json.dumps({'username': username, 'password': password})

    # API request
    response = apiRequest(method, url, headers=headers, data=data)
    if response == '':
        print('Failure of the API request !')
        return 0

    response = json.loads(response.text)
    if 'error_message' in response:
        print(f"Error message [{response['error_message']}]")
        return 0

    # Get token response
    global bearerToken
    bearerToken = response['results']['token']
    print(f"Bearer token : {bearerToken}")
    return 1

"""
Get instance.

:param dbalias : Dbalias name
:return        : Instance
"""
def getInstance(dbalias):
    # Init request
    method  = 'GET'
    url     = f"http://admin-webdba.dbsqware.com/lib/apiUpdate.php?dbalias={dbalias}"
    headers = {
        'Authorization': f"Bearer {bearerToken}",
        'Content-Type': 'application/json'
    }

    # API request
    response = apiRequest(method, url, headers=headers)
    if response == '':
        print('Failure of the API request !')
        return 0

    response = json.loads(response.text)
    if 'error_message' in response:
        print(f"Error message [{response['error_message']}]")
        return 0

    # Get instance
    instance = response['results'][0]
    print(instance)
    return 1

"""
Get instances.

:return : Instances
"""
def getInstances():
    # Init request
    method  = 'GET'
    url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate.php"
    headers = {
        'Authorization': f"Bearer {bearerToken}",
        'Content-Type': 'application/json'
    }

    # API request
    response = apiRequest(method, url, headers=headers)
    if response == '':
        print('Failure of the API request !')
        return 0

    response = json.loads(response.text)
    if 'error_message' in response:
        print(f"Error message [{response['error_message']}]")
        return 0

    # Get instances
    instances = response['results']
    print(instances)
    return 1

"""
Create new instance.

:param data : JSON object data
:return     : Request response
"""
def postInstance(data):
    # Init request
    method  = 'POST'
    url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate.php"
    headers = {
        'Authorization': f"Bearer {bearerToken}",
        'Content-Type': 'application/json'
    }
    data    = json.dumps(data)

    # API request
    response = apiRequest(method, url, headers=headers, data=data)
    if response == '':
        print('Failure of the API request !')
        return 0

    response = json.loads(response.text)
    if 'error_message' in response:
        print(f"Error message [{response['error_message']}]")
        return 0

    print('Insert with success !')
    return 1

"""
Update instance.

:param dbalias : Dbalias name
:param data    : JSON object data
:return        : Request response
"""
def putInstance(dbalias, data):
    # Init request
    method  = 'PUT'
    url     = f"http://admin-webdba.dbsqware.com/lib/apiUpdate.php?dbalias={dbalias}"
    headers = {
        'Authorization': f"Bearer {bearerToken}",
        'Content-Type': 'application/json'
    }
    data    = json.dumps(data)

    # API request
    response = apiRequest(method, url, headers=headers, data=data)
    if response == '':
        print('Failure of the API request !')
        return 0

    response = json.loads(response.text)
    if 'error_message' in response:
        print(f"Error message [{response['error_message']}]")
        return 0

    print("Update with success !")
    return 1

def main():
    # Variables
    username = "toto"
    password = "toto"
    dbalias  = "toto"

    # Get bearer token
    getBearerToken(username, password)

    # Post new instance
    data = {
        "dbalias"       : dbalias,
        "rdbmsname"     : "cassandra",
        "virt_host_name": "AA-TEST-API",
        "host_name"     : "NPW",
        "username"      : "system",
        "port"          : "1430",
        "comments"      : "desc IPS_A",
        "contact"       : "OAY .L",
        "status"        : "ON",
        "client"        : "CUST2",
        "env"           : "PRD3",
        "globalhost"    : "A",
        "custom1"       : "B",
        "custom2"       : "C",
        "comments_upd"  : "insert new instance by API"
    }

    postInstance(data)

    # Get new instance
    getInstance(dbalias)

    # Put new instance
    data = {
        "rdbmsname"     : "mysql",
        "virt_host_name": "AA-TEST-API",
        "host_name"     : "NPW",
        "username"      : "system",
        "port"          : "1430",
        "comments"      : "desc IPS_A",
        "contact"       : "OAY .L",
        "status"        : "OFF",
        "client"        : "CUST2",
        "env"           : "PRD3",
        "globalhost"    : "A",
        "custom1"       : "B",
        "custom2"       : "C",
        "comments_upd"  : "update instance status by API"
    }

    putInstance(dbalias, data)

    # Get all instances
    getInstances()

if __name__ == '__main__':
    main()

PHP

<?php

$bearerToken = "";

/**
 * Does API request.
 * 
 * @param  string  $method : Request method
 * @param  string  $url    : Website url
 * @param  array  $headers : JSON object headers 
 * @param  string  $data   : JSON object data
 * @return string
 */
function apiRequest(string $method, string $url, array $headers = [], $data = '{}'): string
{
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => '',
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_POSTFIELDS     => $data,
        CURLOPT_HTTPHEADER     => $headers,
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    return $response;
}

/**
 * Get bearer token.
 * 
 * @param  string  $username : Account username
 * @param  string  $password : Account password
 * @return bool
 */
function getBearerToken(string $username, string $password): bool
{
    // Init request
    $method  = 'POST';
    $url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate_login.php";
    $headers = ['Content-Type: application/json'];
    $data    = json_encode(['username' => $username, 'password' => $password], JSON_FORCE_OBJECT);

    // API request
    $response = apiRequest($method, $url, $headers=$headers, $data=$data);
    if (empty($response)) {
        echo('Failure of the API request !');
        return 0;
    }

    $response = json_decode($response, true);
    if (array_key_exists('error_message', $response)) {
        echo("Error message [{$response['error_message']}]");
        return 0;
    }

    // Get token response
    global $bearerToken;
    $bearerToken = $response['results']['token'];
    echo("Bearer token : {$bearerToken}");
    return 0;
}

/**
 * Get instance.
 * 
 * @param  string  $dbalias : Dbalias name
 * @return bool
 */
function getInstance(string $dbalias): bool
{
    global $bearerToken;

    // Init request
    $method  = "GET";
    $url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate.php?dbalias={$dbalias}";
    $headers = [
        "Authorization: Bearer {$bearerToken}",
        'Content-Type: application/json'
    ];

    // API request
    $response = apiRequest($method, $url, $headers=$headers);
    if (empty($response)) {
        echo('Failure of the API request !');
        return 0;
    }

    $response = json_decode($response, true);
    if (array_key_exists('error_message', $response)) {
        echo("Error message [{$response['error_message']}]");
        return 0;
    }

    // Get instance
    $instance = $response['results'][0];
    var_dump($instance);
    return 0;
}

/**
 * Get instances.
 * 
 * @return bool
 */
function getInstances(): bool
{
    global $bearerToken;

    // Init request
    $method  = 'GET';
    $url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate.php";
    $headers = [
        "Authorization: Bearer {$bearerToken}",
        'Content-Type: application/json'
    ];

    // API request
    $response = apiRequest($method, $url, $headers=$headers);
    if (empty($response)) {
        echo('Failure of the API request !');
        return 0;
    }

    $response = json_decode($response, true);
    if (array_key_exists('error_message', $response)) {
        echo("Error message [{$response['error_message']}]");
        return 0;
    }

    // Get instances
    $instances = $response['results'];
    var_dump($instances);
    return 0;
}

/**
 * Create new instance.
 * 
 * @param  array  $data : JSON object data
 * @return
 */
function postInstance(array $data): bool
{
    global $bearerToken;

    // Init request
    $method  = 'POST';
    $url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate.php";
    $headers = [
        "Authorization: Bearer {$bearerToken}",
        'Content-Type: application/json'
    ];
    $data    = json_encode($data, JSON_FORCE_OBJECT);

    // API request
    $response = apiRequest($method, $url, $headers=$headers, $data=$data);
    if (empty($response)) {
        echo('Failure of the API request !');
        return 0;
    }

    $response = json_decode($response, true);
    if (array_key_exists('error_message', $response)) {
        echo("Error message [{$response['error_message']}]");
        return 0;
    }

    echo('Insert with success !');
    return 1;
} 

/**
 * Update instance.
 * 
 * @param  string  $dbalias : Dbalias name
 * @param  array  $data     : JSON object data
 * @return bool
 */
function putInstance(string $dbalias, array $data): bool
{
    global $bearerToken;

    // Init request
    $method  = 'PUT';
    $url     = "http://admin-webdba.dbsqware.com/lib/apiUpdate.php?dbalias={$dbalias}";
    $headers = [
        "Authorization: Bearer {$bearerToken}",
        'Content-Type: application/json'
    ];
    $data    = json_encode($data, JSON_FORCE_OBJECT);

    // API request
    $response = apiRequest($method, $url, $headers=$headers, $data=$data);
    if (empty($response)) {
        echo('Failure of the API request !');
        return 0;
    }

    $response = json_decode($response, true);
    if (array_key_exists('error_message', $response)) {
        echo("Error message [{$response['error_message']}]");
        return 0;
    }

    echo("Update with success !");
    return 0;
}

function main(): void
{
    // Variables
    $username = "toto";
    $password = "toto";
    $dbalias  = "toto";

    // Get bearer token
    getBearerToken($username, $password);

    // Post new instance
    $data = [
        "dbalias"        => $dbalias,
        "rdbmsname"      => "cassandra",
        "virt_host_name" => "AA-TEST-API",
        "host_name"      => "NPW",
        "username"       => "system",
        "port"           => "1430",
        "comments"       => "desc IPS_A",
        "contact"        => "OAY .L",
        "status"         => "ON",
        "client"         => "CUST2",
        "env"            => "PRD3",
        "globalhost"     => "A",
        "custom1"        => "B",
        "custom2"        => "C",
        "dbaname"        => $username,
        "comments_upd"   => "insert new instance by API"
    ];

    postInstance($data);

    // Get new instance
    getInstance($dbalias);

    // Put new instance
    $data = [
        "rdbmsname"      => "mysql",
        "virt_host_name" => "AA-TEST-API",
        "host_name"      => "NPW",
        "username"       => "system",
        "port"           => "1430",
        "comments"       => "desc IPS_A",
        "contact"        => "OAY .L",
        "status"         => "OFF",
        "client"         => "CUST2",
        "env"            => "PRD3",
        "globalhost"     => "A",
        "custom1"        => "B",
        "custom2"        => "C",
        "comments_upd"   => "update instance status by API"
    ];

    putInstance($dbalias, $data);

    // Get all instances
    getInstances();
}

main();

?>

Shell

#!/bin/sh

bearerToken=""
tempfile=api_dbSQWare.tmp

<<COMMENTS
    Get bearer token.

    :param username : Account username
    :param password : Account password
    :param tempfile : Temporary file
    :return         : Bearer token
COMMENTS
getBearerToken() {
    username="$1"
    password="$2"
    tempfile="$3"

    curl --location --request POST "http://admin-webdba.dbsqware.com/lib/apiUpdate_login.php" -H "Content-Type:application/json" -d '{"username":"'$username'","password":"'$password'"}' > $tempfile 2>$tempfile.err
	if [ ! -s "$tempfile" ]; then
        echo 'Failure of the API request !'
        return 0
    fi

    if grep -q '"error_message"' "$tempfile"; then
        errorMessage=$(grep '"error_message": "' "$tempfile" | cut -d'"' -f4)
        echo "Error message [$errorMessage]"
        return 0
    fi

    # Get bearer token
    bearerToken=`cat $tempfile|grep '\"token\":\"' | cut -d'"' -f4`
    echo "Bearer token : $bearerToken"
    return 0
}

<<COMMENTS
    Get instance.

    :param dbalias : Dbalias name
    :return        : Instance
COMMENTS
getInstance() {
    dbalias="$1"

    curl --location --request GET "http://admin-webdba.dbsqware.com/lib/apiUpdate.php?dbalias=$dbalias" -H "Authorization: Bearer $bearerToken" -H "Content-Type:application/json" > $tempfile 2>$tempfile.err
	if [ ! -s "$tempfile" ]; then
        echo 'Failure of the API request !'
        return 0
    fi

    if grep -q '"error_message"' "$tempfile"; then
        errorMessage=$(grep '"error_message": "' "$tempfile" | cut -d'"' -f4)
        echo "Error message [$errorMessage]"
        return 0
    fi

    # Get instance
    instance=`cat $tempfile|grep -A 1 '\"results\":'`
    echo "Instance : $instance"
    return 0
}

<<COMMENTS
    Get instances.

    :return : Instances
COMMENTS
getInstances() {
    curl --location --request GET "http://admin-webdba.dbsqware.com/lib/apiUpdate.php" -H "Authorization: Bearer $bearerToken" -H "Content-Type:application/json" > $tempfile 2>$tempfile.err
	if [ ! -s "$tempfile" ]; then
        echo 'Failure of the API request !'
        return 0
    fi

    if grep -q '"error_message"' "$tempfile"; then
        errorMessage=$(grep '"error_message": "' "$tempfile" | cut -d'"' -f4)
        echo "Error message [$errorMessage]"
        return 0
    fi

    # Get instances
    instances=`cat $tempfile|grep -A 1 '\"results\":'`
    echo "Instances : $instances"
    return 0
}

<<COMMENTS
    Create new instance.

    :param data : JSON object data
    :return     : Request response
COMMENTS
postInstance() {
    data="$1"

    curl --location --request POST "http://admin-webdba.dbsqware.com/lib/apiUpdate.php" -H "Authorization: Bearer $bearerToken" -H "Content-Type:application/json" -d "$data" > $tempfile 2>$tempfile.err
	if [ ! -s "$tempfile" ]; then
        echo 'Failure of the API request !'
        return 0
    fi

    if grep -q '"error_message"' "$tempfile"; then
        errorMessage=$(grep '"error_message": "' "$tempfile" | cut -d'"' -f4)
        echo "Error message [$errorMessage]"
        return 0
    fi

    echo 'Insert with success !'
    return 1
}

<<COMMENTS
    Update instance.

    :param dbalias : Dbalias name
    :param data    : JSON object data
    :return        : Request response
COMMENTS
putInstance() {
    dbalias="$1"
    data="$2"

    echo $data > test.tmp
    curl --location --request PUT "http://admin-webdba.dbsqware.com/lib/apiUpdate.php?dbalias=$dbalias" -H "Authorization: Bearer $bearerToken" -H "Content-Type:application/json" -d "$data" > $tempfile 2>$tempfile.err
	if [ ! -s "$tempfile" ]; then
        echo 'Failure of the API request !'
        return 0
    fi

    if grep -q '"error_message"' "$tempfile"; then
        errorMessage=$(grep '"error_message": "' "$tempfile" | cut -d'"' -f4)
        echo "Error message [$errorMessage]"
        return 0
    fi

    echo 'Update with success !'
    return 1
}

main() {
    # Variables
    username="toto";
    password="toto";
    dbalias="toto";

    # Get bearer token
    getBearerToken $username $password $tempfile

    # Post new instance
    data='{"dbalias":"'$dbalias'","rdbmsname":"cassandra","virhosname":"AA-TEST-API","hosname":"NPW","username":"system","port":"1430","comments":"desc IPS_A","contact":"OAY .L","status":"ON","client":"CUST2","env":"PRD3","globalhost":"A","custom1":"B","custom2":"C","comments_upd":"insert new instance by API"}'
    postInstance "$data"

    # Get new instance
    getInstance $dbalias

    # Put new instance
    data='{"rdbmsname":"mysql","virhosname":"AA-TEST-API","hosname":"NPW","username":"system","port":"1430","comments":"desc IPS_A","contact":"OAY .L","status":"OFF","client":"CUST2","env":"PRD3","globalhost":"A","custom1":"B","custom2":"C","comments_upd":"update instance status by API"}'
    putInstance $dbalias "$data"

    # Get all instances
    getInstances
}

main