Orchestrator
Plus récente (Latest)
False
Image de fond de la bannière
Guide de l'utilisateur d'Orchestrator
Dernière mise à jour 30 avr. 2024

Explication des modes d'appel

Les modes d'appel des déclencheurs d'API sont spécifiquement conçus pour créer et suivre des exécutions de tâche dans Orchestrator.

Le défi principal présenté par les communications HTTP est leur caractère intrinsèquement synchrone : en général, le client va envoyer une requête, puis attendre la réponse du serveur. Or, dans le contexte de tâches Robot, il n'est pas possible de garder la connexion ouverte dans Orchestrator jusqu'à la fin de la tâche.

Afin de résoudre ce problème, nous avons utilisé le protocole HTTP afin de modéliser plusieurs modes d'appel. Ces modes reposent sur des méthodes HTTP, des codes d'état et des en-têtes standard afin de créer et surveiller des tâches au sein du système, ainsi qu'obtenir leurs résultats, le tout sans que la connexion demeure inutilement ouverte. Chacun des modes d'appel proposés présente des avantages et des désavantages. Choisissez celui qui conviendra le mieux à vos besoins d'intégration. N'oubliez pas qu'afin de garantir une communication sécurisée, chaque appel nécessite une authentification appropriée via des jetons de porteur.

Important :

Problème connu

Les requêtes peuvent parfois renvoyer une erreur Cloudflare 502 Bad Gateway, causée par le fait qu’un grand nombre de connexions restent actives pendant des intervalles de temps longs. Il est possible que la tâche sous-jacente d’une telle requête s’exécute malgré l’erreur. Vous pouvez donc vérifier son état dans Orchestrator.

Ce problème est intermittent et toutes les requêtes ultérieures fonctionneront comme prévu.

Interrogation asynchrone

Avec ce mode d'appel, un appel est effectué avec le verbe HTTP préconfiguré pour déclencher une nouvelle tâche et recevoir un URI de statut. L'URI de statut doit ensuite être interrogé manuellement jusqu'à la fin de la tâche. À ce moment, l'appel sera redirigé vers un autre point de terminaison, lequel sera utilisé afin de récupérer le résultat de la tâche (sortie ou erreur).

Workflow d'interrogation asynchrone où la finalisation de la tâche dépend d'appels manuels intermédiaires vers l'emplacement de réponse

docs image

L'appel initial est effectué à l'aide du verbe HTTP configuré (GET, POST, PUT, DELETE), lequel va créer la tâche associée dans Orchestrator. Une fois la création de la tâche réussie, le système va répondre avec un code d'état HTTP 202 (Accepted) ainsi qu'un URI de statut dans l'en-tête Emplacement.

Une fois la tâche créée, vous devrez interroger périodiquement son statut. Au cours de ce processus d'interrogation, tant que la tâche est en cours d'exécution, chaque requête GET envoyée à l'URI de statut va renvoyer un code d'état HTTP 200 (OK). Lorsque la tâche est terminée, la requête GET suivante envoyée vers l'URI de statut va renvoyer un code d'état HTTP 303 (See Other) redirigeant vers l'URI de sortie (via l'en-tête Emplacement). Vous devrez suivre l'URI de sortie afin de récupérer le résultat de la tâche (sortie ou erreur).

Pour une authentification réussie, veillez à toujours inclure un jeton de porteur valide dans l'en-tête de chaque appel.

Exemple JavaScript

Cet exemple vous montre comment démarrer une tâche via un déclencheur d'API à partir d'un navigateur en utilisant le mode d'appel par interrogation asynchrone.

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'AsyncRequestReply' // optional argument to force call mode to AsyncRequestReply
}

// if invocation is done by GET, place the parameters in query string and remove the 'Content-Type' header
const invokeRequestOptions = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

const redirectRequestOptions = {
  method: "GET",
  credentials: 'same-origin',
  headers: new Headers({ Authorization: `Bearer ${token}` }),
  redirect: "follow", // this option must be set to follow, otherwise an 'opaqueredirect' response is returned
};

const response = await fetch(url, invokeRequestOptions);
let newLocation = response.headers.get("Location");

// first response should be 202 and have a location header
console.log(`Got ${response.status}, with location: ${newLocation}`);

for (let i = 0; i < 20; i++) {
  await sleep(SLEEP_DURATION);

  // follow the location header to the new endpoint
  const statusResponse = await fetch(newLocation, redirectRequestOptions);

  // if the response was redirected (and automatically followed), then the output endpoint has been reached
  // the output of the job can be found in the body of the response in JSON format
  if (statusResponse.status != 200 || statusResponse.redirected)
  {
    // read the job output
    const output = await statusResponse.json();
    console.log(`Got ${statusResponse.status}, with body: ${JSON.stringify(output)}`);

    break;
}const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'AsyncRequestReply' // optional argument to force call mode to AsyncRequestReply
}

// if invocation is done by GET, place the parameters in query string and remove the 'Content-Type' header
const invokeRequestOptions = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

const redirectRequestOptions = {
  method: "GET",
  credentials: 'same-origin',
  headers: new Headers({ Authorization: `Bearer ${token}` }),
  redirect: "follow", // this option must be set to follow, otherwise an 'opaqueredirect' response is returned
};

const response = await fetch(url, invokeRequestOptions);
let newLocation = response.headers.get("Location");

// first response should be 202 and have a location header
console.log(`Got ${response.status}, with location: ${newLocation}`);

for (let i = 0; i < 20; i++) {
  await sleep(SLEEP_DURATION);

  // follow the location header to the new endpoint
  const statusResponse = await fetch(newLocation, redirectRequestOptions);

  // if the response was redirected (and automatically followed), then the output endpoint has been reached
  // the output of the job can be found in the body of the response in JSON format
  if (statusResponse.status != 200 || statusResponse.redirected)
  {
    // read the job output
    const output = await statusResponse.json();
    console.log(`Got ${statusResponse.status}, with body: ${JSON.stringify(output)}`);

    break;
}

Exemple C#

Cet exemple vous montre comment démarrer une tâche via un déclencheur d'API à partir d'une application C# en utilisant le mode d'appel par interrogation asynchrone.

public async Task<string> AsyncPollingExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds a bearer token on each call
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "AsyncRequestReply" }, // optional argument to force call mode to AsyncRequestReply
    };

    var httpResponseStart = await httpClient.PostAsJsonAsync(url, arguments);
    var redirectUri = httpResponseStart.Headers.Location;

    if (httpResponseStart.StatusCode != HttpStatusCode.Accepted)
        throw new Exception("Could not invoke workflow");

    while (true)
    {
        var httpPollingResponse = await httpClient.GetAsync(redirectUri);

        if (httpPollingResponse.StatusCode == HttpStatusCode.Redirect)
        {
            var outputLocation = httpPollingResponse.Headers.Location;
            var outputResponse = await httpClient.GetAsync(outputLocation);
            var jobOutput = await outputResponse.Content.ReadAsStringAsync();

            return jobOutput;
        }

        await Task.Delay(1000);
    }
}public async Task<string> AsyncPollingExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds a bearer token on each call
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "AsyncRequestReply" }, // optional argument to force call mode to AsyncRequestReply
    };

    var httpResponseStart = await httpClient.PostAsJsonAsync(url, arguments);
    var redirectUri = httpResponseStart.Headers.Location;

    if (httpResponseStart.StatusCode != HttpStatusCode.Accepted)
        throw new Exception("Could not invoke workflow");

    while (true)
    {
        var httpPollingResponse = await httpClient.GetAsync(redirectUri);

        if (httpPollingResponse.StatusCode == HttpStatusCode.Redirect)
        {
            var outputLocation = httpPollingResponse.Headers.Location;
            var outputResponse = await httpClient.GetAsync(outputLocation);
            var jobOutput = await outputResponse.Content.ReadAsStringAsync();

            return jobOutput;
        }

        await Task.Delay(1000);
    }
}

Déclenchement et oubli asynchrones

Le mode d’appel par déclenchement et oubli renvoie un code d'état 200 (OK) lorsqu'une création de tâche a réussi, sans aucune autre information sur la tâche.

Workflow asynchrone par déclenchement et oubli où la tâche est terminée sans appels intermédiaires

docs image

Exemple JavaScript

Cet exemple vous montre comment démarrer une tâche via un déclencheur d'API à partir d'un navigateur en utilisant le mode d'appel par déclenchement et oubli asynchrones.

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth
  
const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'FireAndForget' // optional argument to force call mode to FireAndForget
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

let response = await fetch(url, options);

console.log(`Got ${response.status}`);const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth
  
const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'FireAndForget' // optional argument to force call mode to FireAndForget
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
};

let response = await fetch(url, options);

console.log(`Got ${response.status}`);

Exemple C#

Cet exemple vous montre comment démarrer une tâche via un déclencheur d'API à partir d'une application C# en utilisant le mode d'appel par déclenchement et oubli asynchrones.

public async Task FireAndForgetExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "FireAndForget" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    Console.WriteLine(response.StatusCode);
}public async Task FireAndForgetExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "FireAndForget" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    Console.WriteLine(response.StatusCode);
}

Synchronisation (interrogation longue)

Ce mode d'appel implique qu'un appel initial soit effectué pour bloquer et attendre que la tâche se termine, suivi de plusieurs éventuels appels de blocage et redirections. Enfin, lorsque la tâche est finalisée, le résultat de la tâche (sortie ou erreur) va être récupéré.

En fonction des paramètres du locataire, l'authentification peut être requise pour tous les appels, ou seulement pour l'appel initial.

Workflow de synchronisation (interrogation longue) où le résultat, qu'il soit réussi ou échoué, est renvoyé avec l'appel initial

docs image

Workflow de synchronisation (interrogation longue) où plusieurs appels sont automatiquement effectués vers la fin de la tâche

docs image

L'appel initial est effectué à l'aide du verbe HTTP configuré (GET, POST, PUT, DELETE), lequel va créer la tâche associée dans Orchestrator. Lorsque la création de la tâche a réussi, le système va bloquer l'appel en cours en attendant la fin de la tâche. Lorsque la tâche se termine, l'appel bloqué est libéré et une réponse est renvoyée qui inclut les arguments de sortie de la tâche.

Si après un certain délai d'expiration la tâche n'est pas encore terminée, le système va répondre avec un code d'état HTTP 303 (See Other) redirigeant vers l'URI du statut (via l'en-tête Emplacement). Vous devrez suivre l'URI du statut, lequel est bloqué tant que la tâche n'est pas terminée. Si la tâche n'est pas terminée après un certain délai d'expiration, vous serez de nouveau redirigé vers l'URI de statut, ce qui va créer une boucle de redirection. Une fois la tâche terminée avec succès, le résultat de la tâche (sortie ou erreur) sera récupéré dans le cadre de la réponse HTTP.

Par défaut, tous les appels doivent inclure un jeton de porteur valide pour l'autorisation. Toutefois, si l’option des paramètres du locataire Exiger l'en-tête d'authentification pour les redirections de déclencheurs d'API de synchronisation n’est pas sélectionnée, seul l’appel initial effectué vers le déclencheur nécessite l’en-tête d’authentification. Les appels suivants vers le point de terminaison du statut peuvent être effectués sans en-tête d'autorisation.

La durée de tâche maximale pour ce mode d'appel est de 15 minutes.

Exemple JavaScript

Cet exemple vous montre comment démarrer une tâche via un déclencheur d'API à partir d'un navigateur en utilisant le mode d'appel par synchronisation (interrogation longue).

const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'LongPolling' // optional argument to force call mode to LongPolling
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
  redirect: "follow", // follow redirects automatically
};

let response = await fetch(url, options);
const output = await response.json();

console.log(`Got ${response.status} with body ${JSON.stringify(output)}`);const url = 'https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>';
const token = '<PERSONAL_ACCESS_TOKEN>'; // could also be an access token retrieved via OAuth

const body = {
  'argument1': 123,
  'argument2': 'my string',
  '$callMode': 'LongPolling' // optional argument to force call mode to LongPolling
}

const options = {
  method: 'POST',
  headers: new Headers({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }),
  body: JSON.stringify(body),
  redirect: "follow", // follow redirects automatically
};

let response = await fetch(url, options);
const output = await response.json();

console.log(`Got ${response.status} with body ${JSON.stringify(output)}`);

Exemple C#

Cet exemple vous montre comment démarrer une tâche via un déclencheur d'API à partir d'une application C# en utilisant le mode d'appel par synchronisation (interrogation longue).

public async Task SyncExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "LongPolling" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    while(response.StatusCode == HttpStatusCode.Redirect)
    {
        // in case of redirection, keep following the latest location in the header
        var location = response.Headers.Location;
        response = await httpClient.GetAsync(location);
    }

    // read the job output/error from the last request
    var jobOutput = response.Content.ReadAsStringAsync();

    Console.WriteLine(jobOutput);
}public async Task SyncExample()
{
    const string url = "https://cloud.uipath.com/{organizationName}/{tenantName}/orchestrator_/t/<INVOKE_URL>";
    const string token = "<PERSONAL_ACCESS_TOKEN>"; // could also be an access token retrieved via OAuth

    // create an http client that does not follow redirects and adds Bearer <token> on each call
    // if the follow redirects option is enabled, C# will not add a bearer token by default after the redirect
    var httpClient = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var arguments = new Dictionary<string, object>
    {
        { "argument1", 123 },
        { "argument2", "my string" },
        { "$callMode", "LongPolling" }, // optional argument to force call mode to LongPolling
    };

    var response = await httpClient.PostAsJsonAsync(url, arguments);

    while(response.StatusCode == HttpStatusCode.Redirect)
    {
        // in case of redirection, keep following the latest location in the header
        var location = response.Headers.Location;
        response = await httpClient.GetAsync(location);
    }

    // read the job output/error from the last request
    var jobOutput = response.Content.ReadAsStringAsync();

    Console.WriteLine(jobOutput);
}

Cette page vous a-t-elle été utile ?

Obtenez l'aide dont vous avez besoin
Formation RPA - Cours d'automatisation
Forum de la communauté UiPath
Logo Uipath blanc
Confiance et sécurité
© 2005-2024 UiPath. All rights reserved.