1. Home
  2. /
  3. Developer Guide
  4. /
  5. Rest API
  6. /
  7. Source code examples

Source code examples

You will find on this page sample code source that interacts with the Cirrus Shield REST API. We grouped the examples by either tool or programming language. If you don’t know where to start, start with the Postman collection.

Postman

Download the following Postman collection, it contains a various set of calls to the REST API of Cirrus Shield : Download

.Net

Here are some samples of using Cirrrus Shield’s REST API with .Net

  • Authenticate and get a token
                token = await Http.GetStringAsync(ServiceEndpoint + "/AuthToken?Username=" + username + "&password=" + password);
                token = token.Replace("\"", "");
                Console.WriteLine("New token : " + token);
  • Select a list of projects
        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;
            }
        }
  • Create a record (object : 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;
            }
        }
  • Delete a record (object : 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

Here are some samples of using the REST API with PHP.

  • Create an Opportunity
<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>

  • Select a 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>

  • Get the ID of the Organization

You can get the ID of the Organization by sending the following query: “SELECT Id FROM Organization”

This Query returns a record containing the ID of the Orgnization.

Sample return data in JSON :

{« Data »:{« Organization »:[{« Id »: »1453301944234805898″}]}}

  • Get the timezone of a user

You can get the timezone of a user by sending the following query to the REST API :

SELECT TimeZoneSidKey FROM User WHERE Username=user.name@company.com

This request returns a record that contains the timezone of the user. Here a sample return XML :

<Data>
  <User>
    <TimeZoneSidKey>Europe_Paris</TimeZoneSidKey>
  </User>
</Data>

Was this article helpful to you? No Yes

How can we help?