UiPath Documentation
orchestrator
latest
false
Guide de l'utilisateur d'Orchestrator
Important :
La localisation du contenu nouvellement publié peut prendre 1 à 2 semaines avant d’être disponible.

Explication des modes d'appel

Vue d'ensemble des modes d'appel de déclencheur d'API pour la création et le suivi des exécutions de tâches sur HTTP dans Orchestrator.

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.

To work around this, we’ve used the HTTP protocol to model multiple call modes. These modes rely on standard HTTP methods, status codes, and headers to create, monitor and get the result of jobs within the system, without unnecessarily keeping the connection open.

Each of the proposed call modes has advantages and disadvantages, so you can choose the one that is best suited for your integration needs. Bear in mind that, to ensure secure communication, each call requires proper authentication through bearer tokens.

Important :

Problème connu Les demandes peuvent parfois renvoyer une erreur Cloudflare 502 Bad Gateway, causée par le maintien d’un grand nombre de connexions actives pendant des intervalles de temps prolongés. 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 demandes 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).

Graphique 1. Workflow d'interrogation asynchrone

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.

Once the job is created, you are expected to periodically poll its status. During this polling process, as long as the job is running, each GET request to the status URI returns an HTTP status code 200 (OK). When the job is completed, the next GET request to the status URI returns an HTTP status code 303 (See Other), redirecting to the output URI (via the Location header).

You are expected to follow the output URI to retrieve the job result (output or error).

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 = '{AutomationCloudURL}/{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 = '{AutomationCloudURL}/{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 = "{AutomationCloudURL}/{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 = "{AutomationCloudURL}/{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);
    }
}

Exécution asynchrone sans intervention

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.

Figure 2. Workflow d'exécution asynchrone sans intervention

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 = '{AutomationCloudURL}/{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 = '{AutomationCloudURL}/{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 = "{AutomationCloudURL}/{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 = "{AutomationCloudURL}/{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.

Figure 3. Workflow de synchronisation (interrogation longue) où le résultat est renvoyé avec l'appel initial

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

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.

If after a timeout period the job has not yet completed, the system responds with an HTTP status code 303 (See Other), redirecting to the status URI (via the Location header). You are expected to follow the status URI, which is blocked until the job is completed.

If the job is not completed after a timeout, you are yet again redirected to the status URI, thus creating a redirect loop. Upon successful completion of the job, the job result (output or error) is retrieved as part of the HTTP response.

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 = '{AutomationCloudURL}/{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 = '{AutomationCloudURL}/{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 = "{AutomationCloudURL}/{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.SeeOther)
    {
        // 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 = "{AutomationCloudURL}/{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.SeeOther)
    {
        // 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 ?

Connecter

Besoin d'aide ? Assistance

Vous souhaitez apprendre ? UiPath Academy

Vous avez des questions ? UiPath Forum

Rester à jour