Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Examples of DataWeave in Apex

Here are code samples that demonstrate DataWeave in Apex.

To use DataWeave in Apex, follow these instructions with associated examples.

  • 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>58.0</apiVersion>
    4    <isGlobal>false</isGlobal>
    5</DataWeaveResource>
    6
  • 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