Submit a Script to Run

Submits a script to the server to run.

The request body can include one or more actions by using YAML, JSON or BTXML script. It can also be the path of the script file to run. The "File" property that specifies the script file path and the "KeepStatus" property that specifies how long to keep the script status can both be specified in the request body (by using JSON format) or in the query parameters.

For a list of the actions supported by the Actions API, see Available Actions in the Actions API.

A YAML reference document is available that provides complete details about the specific properties for each action and describes how to combine actions into groups and create arrays of actions to be sent as one script to the server. The YAML actions reference is provided as follows:

 

For more information about this command, including descriptions of any path and request parameters, request body schema, response codes and schemas, and payload examples, refer to the online API reference for this command at the following web page:

Submit a script to run

URI

https://bartendercloud.com/api/actions

The bartendercloud.com domain that is referenced in the URI and in the code examples that follow must be replaced with the contents of the DataCenterURI claim that is extracted from your access token. For more information, refer to Extracting the DataCenterURI Claim.

Path Parameters

None.

Query Parameters

keepStatus

Type: String

Specifies the amount of time to keep the script and its status in the server. The time units can be minutes (m), hours (h), or seconds (s). The time values can be floating point numbers. Valid values resemble "1.5m", "2h", or "300s". The minimum allowed time is 60 seconds. The default value is "60m". Optional.

file

Type: String

Specifies the path of the script file to run. Note that if a value for this query parameter is provided, the script will be retrieved from the path that is specified by the query parameter, and the request body will be ignored. Optional.

wait

Type: String

Specifies the amount of time that the client waits while the script is running before the service returns a status response. The response is returned when the specified amount of time elapses or when the script finishes. If the script has not yet finished when the time elapses, it does continue to run. The time units can be minutes (m) or seconds (s). The time values can be floating point numbers. Valid values resemble "0.5m", "3s", or ".1s". The default value is "0s". The maximum value is "30s". Optional.

messageCount

Type: Integer <int32>

Specifies the maximum number of messages that are retrieved after the wait period elapses and the script runs successfully. When the MessageCount parameter is greater than 0, the specified number of the last logged messages is retrieved. Optional.

messageSeverity

Type: String

Specifies the types of messages that are retrieved after the wait period elapses and the script runs successfully. Valid values are "Error", "Warning", and "Info". When "Error" is specified, only messages that have a severity level of "Error" are retrieved. When "Warning" is specified, messages that have a severity level of "Error" or "Warning" are retrieved. When "Info" is specified, all messages are retrieved. The default value is "Error." Optional.

Examples

You can use any one of several methods to send the command to the server, as shown in the following code samples.

In each of the following samples, you must replace "____PASTE_YOUR_ACCESS_TOKEN_HERE____" with your access token. For more information about your access token, refer to Authentication.

The following example submits a PrintBTWAction script that prints a BarTender document.

Copy
c:\Windows\System32\curl.exe "https://bartendercloud.com/api/actions?Wait=30s&MessageCount=200&MessageSeverity=Info" -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ____PASTE_YOUR_ACCESS_TOKEN_HERE____" 
-d "{ \"PrintBTWAction\": { \"Document\": \"librarian://main/MyDocuments/Simple1_QR.btw\", \"Printer\": \"printer:server1.foobar.com/Zebra_R110Xi4_(300_dpi)\" }  }"

The following example submits scripts that print a BarTender document to PDF, write a message to the log, and download the PDF file contents to the local disk by querying a variable value. The following actions are used: 

  • PrintBTWAction

  • WriteMessageToLogAction

  • ReadFileAction

  • DeleteFileAction

Copy
param (
  [string]$btw_file = "Librarian://main/MyDocuments/Simple1_QR.btw",
  [string]$local_pdf_folder = "d:\",
  [string]$access_token = "____PASTE_YOUR_ACCESS_TOKEN_HERE____"
)

$btc_server_location = "https://bartendercloud.com"

$print_script_template = "
- PrintBTWAction:
    Document: {0}
    Printer: PDF
    QueueAndContinue: false
    VerifyPrintJobIsComplete: true
    MakeUniqueOutputFile: true
    SaveAfterPrint: false    
    ReturnPrintData: true
    ReturnPrintSummary: true
    PrintToFileFolder: Librarian://main/MyDocuments/pdf/
    PrintToFileFileName: Output.pdf
    PrintToFileNameVariable: PrintToFileName

- WriteMessageToLogAction:
    Level: Info
    Message: '%PrintToFileName%'

- ReadFileAction:
    File: '%PrintToFileName%'
    Encoding: Binary

- DeleteFileAction:
    File: '%PrintToFileName%'
"

$script = ($print_script_template -f $btw_file)
Write-Host $script

$content_type = "text/vnd.yaml"

$submit_script_url = "{0}/api/actions?Wait=30s&MessageCount=200&MessageSeverity=Info" -f $btc_server_location
$headers = @{ "Content-Type"=$content_type; "Authorization"=("Bearer {0}" -f $access_token) }

$response = Invoke-WebRequest -Uri $submit_script_url `
                              -Method POST `
                              -Headers $headers `
                              -Body $script
$response

Write-Host ($response.Content | ConvertFrom-Json).Messages

$status = ($response.Content | ConvertFrom-Json).Status
Write-Host ("The script status is {0}." -f $status)

if ($status -eq "RanToCompletion")
{
   # Get the output PDF content by querying the %FileContentsBytes% variable value.
   $status_url = ($response.Content | ConvertFrom-Json).StatusUrl
   $get_pdf_content_url = "{0}/variables/FileContentsBytes" -f $status_url

   Write-Host ("Getting output pdf file path from {0}." -f $get_pdf_content_url)

   $output_pdf_filename = $btw_file.Substring($btw_file.LastIndexOf("/") + 1).Replace(".btw", ".pdf")
   $output_pdf_path = ("{0}\{1}" -f $local_pdf_folder, $output_pdf_filename)

   $headers = @{ "Authorization"=("Bearer {0}" -f $access_token) }
   $response = Invoke-WebRequest -Uri $get_pdf_content_url `
                                 -Method GET `
                                 -Headers $headers `
                                 -OutFile $output_pdf_path

   Write-Host ("Output pdf file is downloaded to {0}" -f $output_pdf_path) -ForegroundColor Yellow -BackgroundColor Blue
}

The following example submits scripts to print a BarTender document to PDF, write a message to the log, and download the PDF file contents to the local disk by using the Librarian API. The following actions are used: 

  • PrintBTWAction

  • WriteMessageToLogAction

  • DeleteFileAction

Copy
param (
  [string]$btw_file = "Librarian://main/MyDocuments/Simple1_QR.btw",
  [string]$local_pdf_folder = "d:\",
  [string]$access_token = "____PASTE_YOUR_ACCESS_TOKEN_HERE____"
)

$btc_server_location = "https://am1.bartendercloud.com" # Replace am1. with eu1. or ap1., depending on your region.

$print_script_template = "
- PrintBTWAction:
    Document: {0}
    Printer: PDF
    QueueAndContinue: false
    VerifyPrintJobIsComplete: true
    MakeUniqueOutputFile: true
    SaveAfterPrint: false    
    ReturnPrintData: true
    ReturnPrintSummary: true
    PrintToFileFolder: Librarian://main/MyDocuments/pdf/
    PrintToFileFileName: Output.pdf
    PrintToFileNameVariable: PrintToFileName

- WriteMessageToLogAction:
    Level: Info
    Message: '%PrintToFileName%'
"

$delete_pdf_script_template = "
- DeleteFileAction:
    File: {0}
"

$script = ($print_script_template -f $btw_file)
Write-Host $script

$content_type = "text/vnd.yaml"
$submit_script_url = "{0}/api/actions?Wait=30s&MessageCount=200&MessageSeverity=Info" -f $btc_server_location
$headers = @{ "Content-Type"=$content_type; "Authorization"=("Bearer {0}" -f $access_token) }

$response = Invoke-WebRequest -Uri $submit_script_url `
                              -Method POST `
                              -Headers $headers `
                              -Body $script
$response

$status = ($response.Content | ConvertFrom-Json).Status
Write-Host ("The script status is {0}." -f $status)

if ($status -eq "RanToCompletion")
{
   # Get the output PDF file path by querying the %PrintToFileName% variable value.
   $status_url = ($response.Content | ConvertFrom-Json).StatusUrl
   $get_pdf_path_url = "{0}/variables/PrintToFileName" -f $status_url
   Write-Host ("Getting output pdf file path from {0}." -f $get_pdf_path_url)

   $headers = @{ "Authorization"=("Bearer {0}" -f $access_token) }
   $response = Invoke-WebRequest -Uri $get_pdf_path_url `
                                 -Method GET `
                                 -Headers $headers
   $pdfpath = $response.Content
   Write-Host ("Output pdf file in the server is '{0}'." -f $pdfpath) -ForegroundColor Yellow -BackgroundColor Blue

   # Download the output PDF file by using the Librarian API.
   $get_pdf_content_url = "{0}/api/librarian/files/path/{1}/content" -f $btc_server_location, [System.Web.HttpUtility]::UrlEncode($pdfpath)

   $output_pdf_filename = $btw_file.Substring($btw_file.LastIndexOf("/") + 1).Replace(".btw", ".pdf")
   $output_pdf_path = ("{0}\{1}" -f $local_pdf_folder, $output_pdf_filename)

   Write-Host ("Downloading pdf from {0}" -f $get_pdf_content_url)

   $response = Invoke-WebRequest -Uri $get_pdf_content_url `
                                 -Method GET `
                                 -Headers $headers `
                                 -OutFile $output_pdf_path

   Write-Host ("Output pdf file is downloaded to {0}" -f $output_pdf_path) -ForegroundColor Yellow -BackgroundColor Blue

   # Delete the PDF file from the server, because it is no longer needed.
   $script = ($delete_pdf_script_template -f $pdfpath)
   Write-Host $script
   $headers = @{ "Content-Type"=$content_type; "Authorization"=("Bearer {0}" -f $access_token) }

   $response = Invoke-WebRequest -Uri $submit_script_url `
                                 -Method POST `
                                 -Headers $headers `
                                 -Body $script
   $response

   Write-Host ("Output pdf file '{0}' in the server has been deleted." -f $pdfpath) -ForegroundColor Yellow -BackgroundColor Blue
}

The following example submits a PrintBTWAction script that prints a BarTender document.

Copy
<!DOCTYPE html>
<html>
<head>
<script>
const actionScript = '\
{\
   "PrintBTWAction": \
   {\
      "Document": "Librarian://main/MyDocuments/Simple1_QR.btw",\
      "Printer": "PDF",\
      "PrintToFileFolder": "Librarian://main/MyDocuments/pdf/",\
      "PrintToFileFileName": "Output.pdf",\
      "SaveAfterPrint": false\
   }\
}\
';
 
btcServerLocation = "https://bartendercloud.com";
accessToken = "____PASTE_YOUR_ACCESS_TOKEN_HERE____";

function sendByFetch()
{
   url = btcServerLocation + "/api/actions?Wait=30s&MessageCount=200&MessageSeverity=Info"
   headers = { "Authorization" : "Bearer " + accessToken }

   fetch(url,
   {
      method: "POST",
      body: actionScript,
      credentials: 'include',
      headers: headers
   })
   .then(function(response)
   {
      var contentType = response.headers.get("content-type");

      if(contentType && contentType.includes("application/json"))
      {
         return response.json();
      }
      throw new TypeError("Oops, we haven't got JSON!");
   })
   .then(function(json)
   {
      document.getElementById("responseOfFetch").innerHTML += ("<p>" + JSON.stringify(json) + "</p>")
   })
   .catch(function(error)
   {
      console.log(error);
      document.getElementById("responseOfFetch").innerHTML += ("<p>" + error + "</p>")
   });
}
</script>
</head>

<body>

<h2>Print via REST API</h2>

<button type="button" onclick="sendByFetch()">Send Print Request</button>
<p id="responseOfFetch"></p>
<br/>

</body>
</html>