Newer Version Available

This content describes an older version of this product. View Latest

Examples of DataWeave in Apex (Beta)

Here are code samples that demonstrate DataWeave in Apex.

This feature is a Beta Service. Customer may opt to try such Beta Service in its sole discretion. Any use of the Beta Service is subject to the applicable Beta Services Terms provided at Agreements and Terms. You can provide feedback and suggestions for the DataWeave in Apex feature in the Trailblazer Community. The beta release of DataWeave in Apex supports packaging of DataWeave scripts within a namespace. However, you can only access scripts within a package, not across different namespaces.

Note

These are instructions to use DataWeave in Apex, with an associated example.

  • Create a DataWeave script source file.
    For example: csvToContacts.dwl.
    1%dw 2.0
    2input records application/csv
    3output application/apex
    4---
    5records map(record) -> {
    6 FirstName: record.first_name,
    7 LastName: record.last_name,
    8 Email: record.email
    9} as Object {class: "Contact"}
    10
  • Create the associated metadata file.

    For example: csvToContacts.dwl-meta.xml.

    1<?xml version="1.0" encoding="UTF-8"?>
    2<DataWeaveResource xmlns="http://soap.sforce.com/2006/04/metadata">
    3    <apiVersion>57.0</apiVersion>
    4</DataWeaveResource>
    5
  • Push the source to the scratch org using Salesforce CLI version v7.151.9 or higher. See Salesforce CLI Release Notes.
  • Invoke the DataWeave script from Apex and check the results from anonymous Apex.
    This example invokes the csvToContacts.dwl script.
    1// CSV data for Contacts
    2String inputCsv = 'first_name,last_name,email\nCodey,"The Bear",codey@salesforce.com'; 
    3DataWeave.Script dwscript = new DataWeaveScriptResource.csvToContacts();
    4DataWeave.Result dwresult = dwscript.execute(new Map<String, Object>{'records' => inputCsv});
    5List<Contact> results = (List<Contact>)dwresult.getValue();
    6
    7Assert.areEqual(1, results.size());
    8Contact codeyContact = results[0];
    9Assert.areEqual('Codey',codeyContact.FirstName);
    10Assert.areEqual('The Bear',codeyContact.LastName);

Extensive code samples that demonstrate the DataWeave in Apex feature are available on Developerforce.

Note