Access Topal via REST API
A few steps are requied, in order to access Topal and its ressources via REST API. Your application will need to cover a few aspects to establish a connection.
The Examples placed here are just indicative and have no claim to completeness. Exception handling was intentionally excluded to improve the readability and
reduce the lines of code.
|
Configuration
|
Contains general settings, which will be needed to access Topal
|
|
Manager Object
|
A Manager Object aggregates working items (e.g. Client, Fiscal year, token etc.)
|
|
Token
|
A token for system authentication
|
Basic Configuration
Create a basic configuration.
public static class Configuration
{
public static string baseurl = "https://livingston:9001/api/v1/"; // "http(s)://<computer name or IP>:9001/api/v1/";
public static string host = "https://livingston:9001"; // "http(s)://<computer name or IP>:9001";
public static string api_version = "/api/v1/";
public static string username = "APIUser";
public static string password = "APIUser#";
public static string defaultFiscalyear = "2022";
public static string defaultClient = "Mon_Bijou_AG_API";
}
class Configuration:
baseurl = "https://livingston:9001/api/v1/"; # "http(s)://<computer name or IP>:9001/api/v1/";
host = "https://livingston:9001"; # "http(s)://<computer name or IP>:9001";
api_version = '/api/v1/'
username = 'APIUser'
password = 'APIUser#'
localization = 'de'
defaultClient = 'Mon_Bijou_AG_API'
defaultFiscalyear = '2022'
Manager
Example of a Manager. The manager handles requests and respective payloads.
Example of a Manager. The manager handles requests and respective payloads.
public class Manager
{
HttpClient httpclient = null;
Credentials credentials = null;
FormUrlEncodedContent loginContent = null;
string token = "";
Client _currentClient = null;
FiscalYear _currentFiscalYear = null;
public Manager()
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
credentials = new Credentials();
httpclient = new HttpClient();
string host = Configuration.host;
string api_version = Configuration.api_version;
string baseurl = host + api_version;
httpclient.BaseAddress = new Uri(baseurl);
loginContent = new FormUrlEncodedContent(credentials.loginParameters);
token = this.getToken(loginContent);
if (token.Equals("")) {
string message = "Can't retrieve token";
Assert.AreEqual(true, false, message);
}
this.httpClient = httpclient;
this.Token = token;
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer" + " " + token);
this.set_current_client(httpClient, Configuration.defaultClient);
this.set_current_fiscalYear(httpClient, Configuration.defaultFiscalyear);
}
public Manager(string client_name, string fiscalyear_name)
{
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
credentials = new Credentials();
httpclient = new HttpClient();
string host = Configuration.host;
string api_version = Configuration.api_version;
string baseurl = host + api_version;
httpclient.BaseAddress = new Uri(baseurl);
loginContent = new FormUrlEncodedContent(credentials.loginParameters);
token = this.getToken(loginContent);
this.httpClient = httpclient;
this.Token = token;
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
this.set_current_client(httpClient, client_name);
this.set_current_fiscalYear(httpClient, fiscalyear_name);
}
public HttpClient httpClient { get; set; }
private string Token { get; set; }
private string getToken(FormUrlEncodedContent loginContent)
{
HttpResponseMessage response = null;
try
{
token = "";
response = httpclient.PostAsync("Token", loginContent).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var tokenResponse = response.Content.ReadAsStringAsync().Result;
dynamic accessToken = JsonConvert.DeserializeObject(tokenResponse);
token = accessToken.access_token;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception information: {0}", ex);
}
return token;
}
public void set_current_client(HttpClient httpClient, string client_name)
{
var response = httpClient.GetAsync(string.Format("clients")).Result;
var clients = JsonConvert.DeserializeObject>(response.Content.ReadAsStringAsync().Result);
Client client = clients.SingleOrDefault(c => (c.name == client_name));
if (client != null)
{
this._currentClient = client;
this._currentClient.isCurrent = true;
}
else {
MessageBox.Show("Default Client not found", "Important Message");
}
}
public void set_current_fiscalYear(HttpClient httpClient, string fiscalyearname)
{
IList fiscalyears = _currentClient.fiscalYears;
FiscalYear fiscalyear = fiscalyears.SingleOrDefault(f => (f.name == fiscalyearname));
if (fiscalyear != null) {
this._currentFiscalYear = fiscalyear;
} else {
MessageBox.Show("Default FiscalYear not found", "Important Message");
}
}
public FiscalYear getCurrentFiscalYear() { return _currentFiscalYear; }
public Client getCurrentClient() { return _currentClient; }
}
class Manager:
"""
Manager class
"""
# Constructor
def __init__(self):
self._token = self._gettoken()
self._headers = {'Content-Type': 'application/x-www-form-urlencoded', # 'text/plain',
'Authorization': '{0}'.format(self._token)}
self._currentclient = self._defaultclient()
self._currentfiscalyear = self._defaultfiscalyear()
def _gettoken(self):
"""
Method to retrieve token for a given user
"""
host = Configuration().host
url = '{0}{1}Token'.format(host, Configuration().api_version)
payload = {'grant_type': 'password',
'username': Configuration().username,
'password': Configuration().password,
'localization': Configuration().localization
}
try:
response = requests.post(url, data=payload, headers={'Content-Type': 'text/plain'})
if response.status_code == 200:
token = response.json()
bearer_token = token['token_type'] + ' ' + token['access_token']
else:
bearer_token = None
except Exception as err:
print("Error: {0}".format(err))
bearer_token = None
return bearer_token
def token(self):
"""
Method doc string
"""
return self._token
def headers(self):
"""
Method doc string
"""
return self._headers
def base_url(self):
"""
Method doc string
"""
# return self.__base_url
return Configuration().baseurl
def _defaultclient(self):
"""
Method doc string
"""
url = '{0}clients'.format(self.base_url())
response = requests.get(url, headers=self.headers())
clients = response.json()
defaultclient = Configuration().defaultclient
if clients is not None:
for client in enumerate(clients, start=0):
if client[1]['name'] == defaultclient:
currentclient = client[1]
break
return currentclient
def _defaultfiscalyear(self):
fiscalyears = self._currentclient['fiscalYears']
defaultfiscalyear = Configuration().defaultfiscalyear
if fiscalyears is not None:
for fiscalyear in enumerate(fiscalyears, start=0):
if fiscalyear[1]['name'] == defaultfiscalyear:
currentfiscalyear = fiscalyear[1]
break
return currentfiscalyear
def setcurrentclient(self, client):
"""
Method doc string
"""
self._currentclient = client
def getcurrentclient(self):
"""
Method doc string
"""
client = self._currentclient
return client
def setcurrentfiscalyear(self, fiscalyear):
"""
Method doc string
"""
self._currentfiscalyear = fiscalyear
def getcurrentfiscalyear(self):
"""
Method doc string
"""
fiscalyear = self._currentfiscalyear
return fiscalyear
# TODO -- submission of parameters
def logout(self):
"""
Method doc string
"""
# GET /api/v1/useraccount/logout
url = '{0}useraccounts/logout'.format(self.base_url())
payload = {'Authorization': self._token}
response = requests.get(url, data=payload)
response = response
return True
Token
Request to retrieve a token from Topal.
private string getToken(FormUrlEncodedContent loginContent)
{
var response = httpclient.PostAsync("Token", loginContent).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var tokenResponse = response.Content.ReadAsStringAsync().Result;
dynamic accessToken = JsonConvert.DeserializeObject(tokenResponse);
token = accessToken.access_token;
}
else {
token = "";
}
return token;
}
def __getToken(self):
host = Configuration().host
url = '{0}{1}Token'.format(host, Configuration().api_version)
parameters = {'grant_type': 'password',
'username': Configuration().username,
'password': Configuration().password,
'localization': Configuration().localization
}
try:
response = requests.get(url, data = parameters)
if response.status_code == 200:
token = response.json()
bearer_token = token['token_type'] + ' ' + token['access_token']
else:
bearer_token = None
except Exception as err:
print("Error: {0}".format(err))
bearer_token = None
return bearer_token