Task API Setup for Apex
To start Dynamo tasks from Apex, use the DynamoTaskJob class on this page. It calls the Task API through a Named Credential, and Dynamo connects back to Salesforce through an External Client App. No API keys or secrets appear in the code.
The class runs as a Queueable job, so you can start it from triggers, other Apex classes or Execute Anonymous. It starts one task per record and handles any number of records.
Before you start
Set up authentication as described in No-code API setup for Salesforce Flows, up to and including the permission set. Skip the External Service and Flow sections, because Apex doesn't use them. You also need a Task API license and an API key from License Manager or Documill Support.
The Apex class depends on these settings:
|
Component |
What the class expects |
|---|---|
|
External Client App |
Client Credentials Flow enabled, with a Run As user. Dynamo connects to Salesforce as this user, so the user needs access to the template file and to the records the template reads. |
|
External Credential |
Custom headers |
|
Named Credential |
Name |
|
Permission set |
External Credential Principal Access. Assign it to every user who starts a job, because the job runs as that user. |
Step 1: Create the Apex class
Create a class named DynamoTaskJob in Setup > Apex Classes, the Developer Console or VS Code, and paste in this code.
/**
* Starts a Dynamo task for each record through the Dynamo Task API.
*
* Usage:
* System.enqueueJob(new DynamoTaskJob(templateId, recordIds));
*
* templateId: ContentDocument ID of the Dynamo application template (DAP)
* recordIds: records to run the template on, one task per record
*/
public with sharing class DynamoTaskJob implements Queueable, Database.AllowsCallouts {
// Name of the Named Credential that points to https://dynamo-api.documill.com
@TestVisible
private static final String NAMED_CREDENTIAL = 'Dynamo_API_Named_Credential';
// Tasks started per job. Further records continue in a new job,
// which keeps each job well within Salesforce's callout limits.
private static final Integer TASKS_PER_JOB = 50;
private final String templateId;
private final List<Id> recordIds;
public DynamoTaskJob(String templateId, List<Id> recordIds) {
this.templateId = templateId;
this.recordIds = recordIds;
}
public void execute(QueueableContext context) {
List<Id> remaining = new List<Id>();
for (Integer i = 0; i < recordIds.size(); i++) {
if (i < TASKS_PER_JOB) {
postTask(recordIds[i]);
} else {
remaining.add(recordIds[i]);
}
}
if (!remaining.isEmpty()) {
System.enqueueJob(new DynamoTaskJob(templateId, remaining));
}
}
private void postTask(Id recordId) {
Map<String, Object> body = new Map<String, Object>{
'template' => templateId,
'params' => new Map<String, String>{
'id' => String.valueOf(recordId)
},
'integration' => new Map<String, String>{
'type' => 'Salesforce',
'serverURL' => URL.getOrgDomainUrl().toExternalForm() + '/services/Soap/u/57.0'
}
};
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:' + NAMED_CREDENTIAL + '/v1/task');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setTimeout(20000);
request.setBody(JSON.serialize(body));
HttpResponse response = new Http().send(request);
if (response.getStatusCode() == 202) {
Map<String, Object> result =
(Map<String, Object>) JSON.deserializeUntyped(response.getBody());
System.debug(LoggingLevel.INFO,
'Dynamo task ' + result.get('taskID') + ' started for ' + recordId);
} else {
System.debug(LoggingLevel.ERROR,
'Dynamo task failed for ' + recordId + ': HTTP '
+ response.getStatusCode() + ' ' + response.getBody());
}
}
}
The Named Credential adds the API key, tenant ID and External Client App credentials to every request. The request body only names the template, the record and the org Dynamo connects back to.
The record ID goes to the template as its id parameter. For Engage eSignature or approval templates, also add 'apiAction' => 'share' to the params map.
Step 2: Create the test class
Salesforce needs test coverage before you can deploy the class to production. Create a class named DynamoTaskJobTest with this code. It uses a mock response, so it doesn't call the Task API.
@IsTest
private class DynamoTaskJobTest {
private static final String TEMPLATE_ID = '069000000000001';
private class DynamoApiMock implements HttpCalloutMock {
private final Integer statusCode;
public DynamoApiMock(Integer statusCode) {
this.statusCode = statusCode;
}
public HttpResponse respond(HttpRequest request) {
Assert.areEqual('callout:' + DynamoTaskJob.NAMED_CREDENTIAL + '/v1/task',
request.getEndpoint());
Assert.areEqual('POST', request.getMethod());
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(request.getBody());
Assert.areEqual(TEMPLATE_ID, body.get('template'));
HttpResponse response = new HttpResponse();
response.setStatusCode(statusCode);
response.setBody(statusCode == 202
? '{"taskID":"t-123","message":"Success"}'
: '{"message":"Forbidden"}');
return response;
}
}
@IsTest
static void startsTask() {
runJob(202);
}
@IsTest
static void completesWhenRequestIsRejected() {
runJob(403);
}
private static void runJob(Integer statusCode) {
Test.setMock(HttpCalloutMock.class, new DynamoApiMock(statusCode));
Test.startTest();
Id jobId = System.enqueueJob(
new DynamoTaskJob(TEMPLATE_ID, new List<Id>{ UserInfo.getUserId() }));
Test.stopTest();
AsyncApexJob job = [SELECT Status FROM AsyncApexJob WHERE Id = :jobId];
Assert.areEqual('Completed', job.Status);
}
}
Step 3: Start a task
To start tasks, enqueue a job with the template's ContentDocument ID and the record IDs:
System.enqueueJob(new DynamoTaskJob('069XXXXXXXXXXXXXXX', recordIds));
For example, this trigger starts a task for each opportunity that moves to Closed Won:
trigger OpportunityDynamoTask on Opportunity (after update) {
List<Id> closedWon = new List<Id>();
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName == 'Closed Won' && oldOpp.StageName != 'Closed Won') {
closedWon.add(opp.Id);
}
}
if (!closedWon.isEmpty()) {
System.enqueueJob(new DynamoTaskJob('069XXXXXXXXXXXXXXX', closedWon));
}
}
The template's ContentDocument ID is different in a sandbox and in production. Keep it in a custom label or custom metadata record instead of in code.
Check the result
The Task API runs tasks asynchronously. An accepted task returns HTTP 202 and a task ID, and Dynamo then runs the template. To test the setup:
-
In the Developer Console, open Debug > Open Execute Anonymous Window and run the Step 3 line with a real template ID and record ID.
-
In Setup > Apex Jobs, check that the
DynamoTaskJobjob has the status Completed. -
In the debug log, find
Dynamo task <task ID> started for <record ID>. A rejected request logsDynamo task failed for <record ID>with the HTTP status and Dynamo's message. -
To see whether the task finished and what it produced, call Task Status with the task ID. Tasks are available for 24 hours after they're posted.
Troubleshooting
|
Symptom |
Cause |
Fix |
|---|---|---|
|
HTTP 401 in the debug log |
The tenant ID or API key header is missing. |
Check the custom headers on the External Credential, and that Allow Formulas in HTTP Header is selected on the Named Credential. |
|
HTTP 403 in the debug log |
The tenant ID or API key is invalid, or the API licenses are used up. |
Check both values in the External Credential. If they're correct, contact support@documill.com. |
|
HTTP 400 in the debug log |
The request is invalid, often because of a wrong template ID. |
Use the ContentDocument ID of the DAP file. Dynamo's message in the log gives details. |
|
The job fails with "We couldn't access the credential(s)" |
The user who started the job doesn't have access to the External Credential. |
Assign that user the permission set with External Credential Principal Access. |
|
The task is accepted but finishes with errors |
The External Client App's Run As user can't read the template file or the record. |
Give the Run As user access to both. |
|
Calls stop working after a sandbox refresh |
The refreshed org has a new org ID and needs a new API key. |
Set |