Général:FAQ API MAJ

De WikiFr_dbSQWare
Aller à la navigation Aller à la recherche

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

v_bearer_token=""
v_tempfile=api_dbSQWare.tmp

<<COMMENTS
 f_get_bearer_token recovers bearer token

 :param v_username : account username
 :param v_password : account password
 :param v_tempfile : temporary file
 :return           : bearer token
COMMENTS
f_get_bearer_token(){
 v_username="$1"
 v_password="$2"
 v_tempfile="$3"

 curl --location --request POST "http://my_sqwareweb_url/lib/apiUpdate_login.php" -H "Content-Type:application/json" -d '{"username":"'$v_username'","password":"'$v_password'"}' > $v_tempfile 2>$v_tempfile.err
if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
then
	 # Get bearer token
	v_bearer_token=`cat $v_tempfile|grep '\"token\":\"' | cut -d'"' -f4`
	 echo "Bearer token : $v_bearer_token"
	return 0
else
	v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
	 echo "Error message [$v_error_message]"
	return 1
fi
}

<<COMMENTS
 f_get_instance recovers instance object

 :param v_dbalias : dbalias name
 :return          : instance object
COMMENTS
f_get_instance(){
 v_dbalias="$1"

 curl --location --request GET "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias=$v_dbalias" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" > $v_tempfile 2>$v_tempfile.err
if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
then
	 # Get instance
	 v_instance=`cat $v_tempfile|grep -A 1 '\"results\":'`
	 echo "Instance : $v_instance"
	return 0
else
	v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
	 echo "Error message [$v_error_message]"
	return 1
fi
}

<<COMMENTS
 f_get_instances recovers instances objects

 :return : instances objects
COMMENTS
f_get_instances(){
 curl --location --request GET "http://my_sqwareweb_url/lib/apiUpdate.php" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" > $v_tempfile 2>$v_tempfile.err
if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
then
	# Get instances
	v_instances=`cat $v_tempfile|grep -A 1 '\"results\":'`
	 echo "Instances : $v_instances"
	return 0
else
	 v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
	 echo "Error message [$v_error_message]"
	return 1
fi
}

<<COMMENTS
 f_post_instance create new instance object

 :param t_data : JSON object data
 :return       : request response
COMMENTS
f_post_instance(){
 t_data="$1"

 curl --location --request POST "http://my_sqwareweb_url/lib/apiUpdate.php" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" -d "$t_data" > $v_tempfile 2>$v_tempfile.err
if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
then
	echo "Insert with success !"
	return 0
else
	v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
	 echo "Error message [$v_error_message]"
	return 1
fi
}

<<COMMENTS
 f_put_instance update instance object

 :param v_dbalias : dbalias name
 :param t_data    : JSON object data
 :return          : request response
COMMENTS
f_put_instance(){
 v_dbalias="$1"
 t_data="$2"

 echo $t_data > test.tmp
 curl --location --request PUT "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias=$v_dbalias" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" -d "$t_data" > $v_tempfile 2>$v_tempfile.err
if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
then
	echo "Update with success !"
	return 0
else
	v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
	 echo "Error message [$v_error_message]"
	return 1
fi
}

main(){
 # Variables
 v_username="toto";
 v_password="toto";
 v_dbalias="toto";

 # Get bearer token
 f_get_bearer_token $v_username $v_password $v_tempfile

 # Post new instance
 t_data='{"dbalias":"'$v_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":"'$v_username'","comments_upd":"insert new instance by API"}'
 f_post_instance "$t_data"

 # Get new instance
 f_get_instance $v_dbalias

 # Put new instance
 t_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"}'
 f_put_instance $v_dbalias "$t_data"

 # Get all instances
 f_get_instances
}

main