Vous trouverez sur cette page des exemples de code source interagissant avec l’API REST de Cirrus Shield. Nous avons classé ces exemples par outil ou langage de programmation. Le plus simple est de démarrer avec la collection Postman.
Postman
Téléchargez la collection suivante qui contient différents appels à l’API REST de Cirrus Shield : Télécharger
.Net
Voici quelques exemples de l’utilisation de l’API REST de Cirrus Shield avec du code .Net.
- S’authentifier
token = await Http.GetStringAsync(ServiceEndpoint + "/AuthToken?Username=" + username + "&password=" + password);
token = token.Replace("\"", "");
Console.WriteLine("New token : " + token);
- Sélectionner une liste de projets
public async Task<List<Project>> GetActiveProjects()
{
try
{
List<Project> listOfActiveProjects = new List<Project>();
var csProjectsStr = await Http.GetStringAsync(ServiceEndpoint + "/Query?authToken=" + token + "&selectQuery=Select+Id,Name+from+Project+where+Status='In+Progress'");
XElement csProjectsXml = XElement.Parse(csProjectsStr);
foreach (XElement xe in csProjectsXml.Descendants("Project"))
{
Project prj = new Project() { Id = xe.Element("Id").Value, Name = xe.Element("Name").Value };
listOfActiveProjects.Add(prj);
}
return listOfActiveProjects.OrderBy(o => o.Name).ToList();
}
catch (Exception e)
{
throw e;
}
}
- Sauvegarder un enregistrement (objet Time)
public async Task<Time> SaveTimeItem(Time timeItem)
{
try
{
var xmlData = new XElement("Data", "");
var xmlTime = new XElement("Time", "");
xmlTime.Add(new XElement("Id", timeItem.Id));
if (string.IsNullOrEmpty(timeItem.Name))
xmlTime.Add(new XElement("Name", timeItem.Name));
xmlTime.Add(new XElement("OwnerId", timeItem.OwnerId));
xmlTime.Add(new XElement("Work_Site", timeItem.Work_Site));
xmlTime.Add(new XElement("Date", timeItem.Date.ToString("yyyy-MM-dd"))); // DateTime format: yyyy-MM-dd HH-mm-sszz
xmlTime.Add(new XElement("Description", timeItem.Description));
xmlTime.Add(new XElement("Hours", timeItem.Hours.ToString(System.Globalization.CultureInfo.CurrentCulture)));
xmlTime.Add(new XElement("Project", timeItem.ProjectId));
xmlTime.Add(new XElement("Project_Budget", timeItem.ProjectBudgetId));
xmlTime.Add(new XElement("Check_out_Date_Time", timeItem.CheckOutDateTime.ToString("yyyy-MM-dd HH:mm:sszz")));
xmlTime.Add(new XElement("Check_in_Date_Time", timeItem.CheckInDateTime.ToString("yyyy-MM-dd HH:mm:sszz")));
xmlData.Add(xmlTime);
var content = new StringContent("=" + HttpUtility.UrlEncode(xmlData.ToString()), Encoding.UTF8, "application/x-www-form-urlencoded"); // we could also use FormUrlEncodedContent
var response = await Http.PostAsync(ServiceEndpoint + "/DataAction/Time?authToken=" + token + "&action=upsert&matchingFieldName=id", content);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
var apiResponse = XElement.Parse(responseBody);
Console.WriteLine(" ### Saving Time Item PAYLOAD \n" + apiResponse + "\n ### ");
timeItem.Id = apiResponse.Descendants("id").First().Value;
if (string.IsNullOrEmpty(timeItem.Name))
timeItem.Name = apiResponse.Descendants("name").First().Value;
if ((responseStatusCode != System.Net.HttpStatusCode.OK) || (apiResponse.Descendants("Success").First().Value == "False"))
{
Console.WriteLine("ErrorMessage : " + apiResponse.Descendants("ErrorMessage").First().Value);
Console.WriteLine("Response Body : " + responseBody);
throw new Exception ("There was an issue saving this Time, the server replied with the following information -- Status code: " + responseStatusCode + " -- Error Message : " + apiResponse.Descendants("ErrorMessage").First().Value + " -- Please contact your administrator\n");
}
return timeItem;
}
catch (Exception e)
{
throw e;
}
}
- Supprimer un enregistrement (objet Time) :
public async Task<bool> DeleteTimeItem(Time timeItem)
{
try
{
var xmlData = new XElement("Data", "");
var xmlTime = new XElement("Time", "");
xmlTime.Add(new XElement("Id", timeItem.Id));
xmlData.Add(xmlTime);
var content = new StringContent("=" + HttpUtility.UrlEncode(xmlData.ToString()), Encoding.UTF8, "application/x-www-form-urlencoded"); // we could also use FormUrlEncodedContent
var response = await Http.PostAsync(ServiceEndpoint + "/DataAction/Time?authToken=" + token + "&action=delete&matchingFieldName=id", content);
Console.WriteLine("REST API DELETE call (careful with what you do on production data): " + response);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
if (responseStatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception("There was an issue deleting this Time, the server replied with the following error -- Status code: " + responseStatusCode + " -- Response body : " + responseBody + " -- Please contact your administrator\n");
}
return true;
}
catch (Exception e)
{
throw e;
}
}
PHP
Voici quelques exemples d’utilisation de l’API REST avec PHP.
- Créer une Opportunité
<html>
<head>
<title>REST API Test - Create Opportunity</title>
</head>
<body>
<?php
function authenticate($username, $password)
{
$login = [
"Username" => $username,
"password" => $password,
];
$url = sprintf("%s?%s", "https://www.cirrus-shield.net/RestApi/AuthToken", http_build_query($login));
$client = curl_init();
curl_setopt($client, CURLOPT_VERBOSE, true);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_URL, $url);
$response = curl_exec($client);
curl_close($client);
return $response;
}
function createOpportunity($urlParams, $xmlData)
{
$url = sprintf("%s?%s", "http://www.cirrus-shield.net/RestApi/DataAction/Opportunity", http_build_query($urlParams));
$headers = array(
"Content-Type: application/x-www-form-urlencoded",
"charset=utf-8",
);
$client = curl_init();
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_URL, $url);
curl_setopt($client, CURLOPT_HTTPHEADER, $headers);
curl_setopt($client, CURLOPT_POSTFIELDS, "=" . $xmlData);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLINFO_HEADER_OUT, true);
curl_setopt($client, CURLOPT_SSLVERSION, 6);
$response = curl_exec($client);
curl_close($client);
echo "<br><br> HTTP Response content = ";
print_r('<pre>');
var_dump($response);
print_r('</pre>');
echo "<br><br> POST content = ";
return $response;
}
$username = "mail@mail.com";
$password = "password";
$authToken = authenticate($username, $password);
$authToken = str_replace("", "", $authToken);
if ($authToken != '') {
$opportunityName = filter_input(INPUT_POST, 'Name', FILTER_SANITIZE_STRING);
$opportunityOwner = filter_input(INPUT_POST, 'Owner', FILTER_SANITIZE_STRING);
$xmlData =
"<Data>"
. "<Opportunity>"
. "<Id></Id>"
. "<Name>Test3</Name>"
. "<OwnerId>user.email@company.com</OwnerId>"
. "</Opportunity>"
. "</Data>";
$urlParams = ["authToken" => $authToken, "action" => "insert", "matchingFieldName" => "Id",];
$createOpportunity = createOpportunity($urlParams, $xmlData);
} else {
echo "<br>Authentication Failed";
}
?>
</body>
</html>
- Sélectionner un Lead
<html>
<head>
<title>REST API Test - Select Lead</title>
</head>
<body>
<?php
function authenticate($username, $password)
{
$login = [
"Username" => $username,
"password" => $password,
];
$url = sprintf("%s?%s", "https://www.cirrus-shield.net/RestApi/AuthToken", http_build_query($login));
$client = curl_init();
curl_setopt($client, CURLOPT_VERBOSE, true);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_URL, $url);
$response = curl_exec($client);
curl_close($client);
return $response;
}
function SelectLead($authToken)
{
$selectparam = [
"authToken" => $authToken,
"selectQuery" => "SELECT Email FROM Lead WHERE Last_Name=Smith",
];
$url = sprintf("%s?%s", "https://www.cirrus-shield.net/RestApi/Query", http_build_query($selectparam));
$client = curl_init();
curl_setopt($client, CURLOPT_VERBOSE, true);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_URL, $url);
$response = curl_exec($client);
curl_close($client);
$array_data = json_decode($response, true);
print_r('<pre>');
var_dump($response);
print_r('</pre>');
return $response;
}
$username = "mail@mail.com";
$password = "password";
$authToken = authenticate($username, $password);
$authToken = str_replace("", "", $authToken);
if ($authToken != '') {
$selectLead = SelectLead($authToken);
} else {
echo "<br>Authentication Failed";
} ?>
</body>
</html>
- Obtenir l’Id de l’Organisation
Vous pouvez obtenir l’ID d’organisation à l’aide de l’API RESTen envoyant la requête de sélection suivante : “SELECT Id FROM Organization”
Cette requête retourne un enregistrement contenant l’ID de l’organisation.
Exemple d’enregistrement retourné (en JSON):
{« Data »:{« Organization »:[{« Id »: »1453301944234805898″}]}}
- Obtenir le fuseau horaire de l’utilisateur
Vous pouvez obtenir le fuseau horaire de l’utilisateur à l’aide de l’API REST en envoyant la requête de sélection suivante à la méthode de l’API :
SELECT TimeZoneSidKey FROM User WHERE Username=user.name@company.com
Cette requête renvoie un enregistrement qui contient le fuseau horaire de l’utilisateur. Exemple d’enregistrement retourné (en XML):
<Data>
<User>
<TimeZoneSidKey>Europe_Paris</TimeZoneSidKey>
</User>
</Data>