1. Accueil
  2. /
  3. Guide Développeur
  4. /
  5. Rest API
  6. /
  7. Exemples de code sources

Exemples de code sources

⚠️ Le paramètre authToken ci-dessous correspond à l’ancienne méthode d’authentification. Pour toute nouvelle intégration, utilisez plutôt OAuth 2.0 et envoyez le jeton d’accès dans l’en-tête Authorization: Bearer <access_token> plutôt qu’en paramètre d’URL. Voir 1. AuthToken — Authentification OAuth 2.0 pour la documentation complète.

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 (OAuth 2.0)

Utilisez le flux Client Credentials pour obtenir un jeton d’accès, puis attachez-le à chaque appel via l’en-tête Authorization: Bearer. Voir 1. AuthToken — Authentification OAuth 2.0 pour le détail complet et comment obtenir un jeton.

var accessToken = await GetOAuthAccessTokenAsync(); // Flux Client Credentials — voir le guide OAuth 2.0
Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
  • 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?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?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?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é

Cet exemple utilisait auparavant l’ancien flux authToken. Authentifiez-vous désormais via OAuth 2.0 (flux Client Credentials) et incluez le jeton d’accès dans l’en-tête Authorization: Bearer <access_token> de chaque appel curl (via CURLOPT_HTTPHEADER) plutôt qu’en paramètre d’URL. Voir 1. AuthToken — Authentification OAuth 2.0 pour un exemple complet d’obtention du jeton.

  • Sélectionner un Lead

Cet exemple utilisait auparavant l’ancien flux authToken. Authentifiez-vous désormais via OAuth 2.0 (flux Client Credentials) et incluez le jeton d’accès dans l’en-tête Authorization: Bearer <access_token> de chaque appel curl (via CURLOPT_HTTPHEADER) plutôt qu’en paramètre d’URL. Voir 1. AuthToken — Authentification OAuth 2.0 pour un exemple complet d’obtention du jeton.

Cet article vous a-t-il été utile ? Non Oui

Comment pouvons-nous aider ?