Newer Version Available

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

Examples of DataWeave in Apex (Developer Preview)

Here are code samples that demonstrate DataWeave in Apex.

Feature is available as a developer preview. Feature isn’t generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements. All commands, parameters, and other features are subject to change or deprecation at any time, with or without notice. Don't implement functionality developed with these commands or tools in a production environment. You can provide feedback and suggestions for the DataWeave in Apex feature in the Trailblazer Community.

Note

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

  • Create a scratch org that has the DataWeaveInApex feature included in its definition file. See Build Your Own Scratch Org Definition File.
  • 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>56.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 = DataWeave.Script.createScript('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