Hands On Using DataWeave in Salesforce Apex

Hands On Using DataWeave in Salesforce Apex

In the previous blog, the local development environment for DataWeave was established -with VS Code configured, the Anypoint Code Builder – DataWeave Extension installed, the Salesforce Extension Pack connected, and the .dwl script files created and ready for transformation logic. With the development environment fully in place, the next step is putting it to work. DataWeave in Apex is a powerful, declarative transformation engine that enables developers to handle complex data formats such as XML, JSON, and CSV with minimal code and maximum efficiency. 

 
Why DataWeave in Apex? 

DataWeave introduces a modern, declarative approach to data transformation  applicable across both inbound and outbound integration scenarios. Key advantages include: 

  • Multi-Format Support : Seamlessly handles XML, JSON, and CSV in both directions. 
  • Reduced Code Complexity : Eliminates verbose Dom.Document and JSON Parser logic in Apex. 
  • Reusable .dwl Scripts : Scripts stored as static resources promote DRY (Don’t Repeat Yourself) principles across multiple integration flows. 
  • Type Safety and Schema Awareness : Enforces type coercion and format validation, reducing runtime errors caused by data type mismatches. 
  • MuleSoft Alignment : Enables a unified transformation strategy across MuleSoft integration flows and Salesforce Apex logic. 

Two Proof of Concepts (POCs) are demonstrated here, together showcasing a complete bidirectional integration pattern built on the foundation established: 

  • POC 1 – Consuming an external XML API and creating Salesforce records from the response. 
  • POC 2 – Retrieving Salesforce records, transforming them into JSON, and pushing the data to an external REST API via HTTP POST. 

 

POC 1: Consuming an XML API and Creating Salesforce Records

Solution Overview 

The inbound integration follows a structured, step-by-step approach: 

  1. API Callout : Salesforce initiates an HTTP GET callout to an external system to retrieve data. 
  1. XML Response Handling : The external API returns data in XML format, which is not natively consumable by Apex without transformation. 
  1. Data Transformation with DataWeave : A DataWeave script (.dwl) converts the raw XML response into Apex-compatible objects using a declarative, schema-aware approach. 
  1. Data Mapping :The transformed data is mapped to standard or custom Salesforce objects such as Account or Contact. 
  1. Record Creation via DML : Salesforce performs insert or upsert DML operations to persist the transformed data as Salesforce records. 

Why DataWeave for XML Parsing? 

In Apex, working with XML requires writing a lot of step-by-step code to go through the data, which makes it complex and hard to understand. DataWeave makes this easier by allowing you to write short and clear code where you directly define what output you want. This reduces the amount of code and helps avoid errors in real projects. 

DataWeave Script : Transforming XML to Apex Objects 

The following DataWeave script (xmlToJsonPart2.dwl) accepts the raw XML response from the external API, traverses the RSS feed structure, and maps each item to a Salesforce Account object. 

Input XML: 

<?xml version='1.0' encoding='UTF-8'?>
<rss version="2.0">
  <channel>
    <title><![CDATA[ BBC News ]]></title>
    <description><![CDATA[ BBC News - World ]]></description>
    <link>https://www.bbc.co.uk/news/world</link>
    <image>
      <url>https://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif</url>
      <title>BBC News</title>
      <link>https://www.bbc.co.uk/news/world</link>
    </image>
    <generator>RSS for Node</generator>
    <lastBuildDate>Fri, 10 Apr 2026 12:31:53 GMT</lastBuildDate>
    <atom:link xmlns:atom="http://www.w3.org/2005/Atom" href="https://feeds.bbci.co.uk/news/world/rss.xml" rel="self" type="application/rss+xml"/>
    <copyright><![CDATA[ Copyright: (C) British Broadcasting Corporation, see https://www.bbc.co.uk/usingthebbc/terms-of-use/#15metadataandrssfeeds for terms and conditions of reuse. ]]></copyright>
    <language><![CDATA[ en-gb ]]></language>
    <ttl>15</ttl>
    <item>
      <title><![CDATA[ Trump says Iran's handling of Strait of Hormuz is 'not the agreement we have' ]]></title>
      <description><![CDATA[ The US president accused Iran of "doing a very poor job" with the waterway as Israel and Lebanon to begin peace talks. ]]></description>
      <link>https://www.bbc.com/news/articles/cge0xre3d27o</link>
      <guid isPermaLink="false">https://www.bbc.com/news/articles/cge0xre3d27o#0</guid>
      <pubDate>Fri, 10 Apr 2026 02:10:44 GMT</pubDate>
      <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" width="240" height="135" url="https://ichef.bbci.co.uk/ace/standard/240/cpsprodpb/fb74/live/ad515bf0-347e-11f1-bbf7-7db5bb17fba6.jpg"/>
    </item>
    <item>
      <title><![CDATA[ Ceasefire or no ceasefire, the Middle East's reshuffling is not yet done ]]></title>
      <description><![CDATA[ Both sides have reason to end the war but share no common ground. ]]></description>
      <link>https://www.bbc.com/news/articles/cp3l4yk5rlgo</link>
      <guid isPermaLink="false">https://www.bbc.com/news/articles/cp3l4yk5rlgo#0</guid>
      <pubDate>Thu, 09 Apr 2026 23:01:47 GMT</pubDate>
      <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" width="240" height="135" url="https://ichef.bbci.co.uk/ace/standard/240/cpsprodpb/5219/live/f4717b10-3428-11f1-8606-05fe34b06e1b.jpg"/>
    </item>
    <item>
      <title><![CDATA[ Melania Trump denies ties to Jeffrey Epstein and urges hearing for survivors ]]></title>
      <description><![CDATA[ She called rumours that Epstein introduced her to Donald Trump "mean-spirited attempts to defame my reputation". ]]></description>
      <link>https://www.bbc.com/news/articles/c3ex07l1qvpo</link>
      <guid isPermaLink="false">https://www.bbc.com/news/articles/c3ex07l1qvpo#0</guid>
      <pubDate>Fri, 10 Apr 2026 08:37:05 GMT</pubDate>
      <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" width="240" height="135" url="https://ichef.bbci.co.uk/ace/standard/240/cpsprodpb/e750/live/ec957be0-349f-11f1-9d5c-8ba507d7dbde.jpg"/>
    </item>
  </channel>
</rss>

Apex Logic : HTTP Callout and DataWeave Execution 

The Apex class DataWeave_PART2 handles the HTTP GET callout to the external XML API endpoint. Once the response is received, the raw XML body is passed into the DataWeave script as input. After the DataWeave script executes, the result is cast from a generic List<Object> into a typed List<Account>. The records are then inserted into Salesforce using a standard DML insert statement, completing the inbound integration flow. 

Output : 

 

POC 2: Pushing Salesforce Data to an External REST API via HTTP POST

Overview 

The outbound integration pattern positions Salesforce as the data producer  retrieving records from its database, transforming them into a structured JSON payload, and dispatching them to an external REST API that accepts data in JSON format over HTTP POST. 

This pattern is widely adopted in enterprise integrations where downstream systems  such as ERP platforms, marketing tools, data warehouses, or third-party SaaS applications  require Salesforce data in a standardized JSON format. 

Solution Overview 

  1. Record Retrieval via SOQL : Apex queries the required Salesforce records, fetching relevant fields from objects such as Account, Contact, or Order. 
  1. Data Serialization with DataWeave : A DataWeave transformation script converts the Apex objects into a well-structured JSON payload, applying field mappings, renaming conventions, and data type conversions as required by the target API contract. 
  1. HTTP POST Callout : Salesforce constructs an HttpRequest object, sets the method to POST, attaches the serialized JSON as the request body, and configures appropriate headers  including Content-Type: application/json and authentication headers such as Bearer tokens or API keys. 
  1. Response Handling : The HTTP response is captured and evaluated. Success responses (2xx) confirm data receipt, while error responses (4xx or 5xx) trigger exception handling or retry logic. 
  1. Logging and Error Management : Integration logs or platform events track callout outcomes, supporting observability and debugging in production environments. 

DataWeave Script : Serializing Salesforce Records to JSON 

The following DataWeave script (contactSerialize.dwl) accepts a list of Salesforce Contact records as input and transforms them into a structured JSON payload. It maps FirstName and LastName into a combined name field, and applies default fallback values for email, phone, and department when field data is absent  ensuring the outbound payload is always well-formed and API-compliant. 

Input : 

Apex Logic : SOQL Query, DataWeave Execution, and HTTP POST 

The Apex class DataWeave_Serialization orchestrates the full outbound flow in three steps. First, it retrieves Contact records from Salesforce via SOQL. Second, the records are passed into the DataWeave script, which serializes them into a JSON string. Third, the JSON payload is dispatched to the external REST API endpoint t using an HttpRequest configured with the POST method and Content-Type: application/jsonheader.  

Output: 

Key Technical Considerations 

  • Named Credentials : Endpoint URLs and authentication are managed securely through Named Credentials, eliminating hardcoded values in Apex classes. 
  • Remote Site Settings : External endpoints must be registered under Remote Site Settings to authorize outbound callouts from Salesforce. 
  • Governor Limits : Apex enforces a limit of 100 HTTP callout statements per transaction with a timeout of 120 seconds. Bulk scenarios must leverage asynchronous patterns such as Queueable or Batch Apex. 
  • JSON Structure Validation : DataWeave enforces strict field mapping and type coercion, ensuring the outbound payload conforms to the target API schema without manual string construction. 
  • Error Response Parsing : DataWeave can parse error responses from external APIs, extracting meaningful messages for logging or alerting workflows. 

Limitations of DataWeave in Apex 

While DataWeave in Apex is a powerful capability, it is important to be aware of its current limitations before adopting it in production: 

  • Static Resource Dependency : DataWeave scripts must be stored and deployed as static resources (.dwl files). They cannot be created or modified dynamically at runtime within Apex. 
  • Governor Limit Exposure : DataWeave transformations executed within synchronous Apex transactions are subject to standard Salesforce governor limits, including CPU time and heap size limits, which can be impacted by large payload transformations. 
  • Limited Debugging Support : Unlike standard Apex, DataWeave scripts do not have native debug log support within Salesforce. Errors during script execution surface as generic exceptions, making troubleshooting more reliant on the DataWeave Playground for pre-validation. 
  • No Dynamic Script Generation : DataWeave scripts are static by nature. Conditional transformation logic must be built within the script itself and cannot be generated or modified programmatically from Apex at runtime. 
  • Learning Curve :Developers familiar only with Apex may require additional time to learn DataWeave’s functional, expression-based syntax, especially for complex nested transformations. 
  • Output Type Constraints : DataWeave in Apex currently supports a defined set of output types such as application/json, application/xml, and application/apex. Not all DataWeave output formats available in MuleSoft are supported within the Salesforce Apex context. 
  • Callout Restrictions : DataWeave scripts themselves cannot initiate HTTP callouts. All external API interactions must be handled by Apex, with DataWeave limited strictly to the transformation layer. 

DataWeave Playground 

Before diving into the POCs, it is worth understanding the DataWeave Playground  an interactive, browser-based environment provided by MuleSoft that allows developers to write, test, and validate DataWeave transformation scripts without any setup or deployment.

Why Use the DataWeave Playground? 

When working with complex data transformations  especially across formats like XML, JSON, and CSV testing transformation logic in isolation before integrating it into Salesforce is invaluable. The Playground provides an instant feedback loop that drastically reduces development and debugging time. 

How It Works 

  • The Payload panel on the left accepts the input data  XML, JSON, CSV, or any supported format. 
  • The Script panel in the center is where the DataWeave transformation logic is written. 
  • The Output panel on the right displays the transformed result in real time. 

Developers can prototype, validate, and fine-tune their .dwl scripts entirely in the browser before deploying them as Salesforce static resources. 

Benefits of the DataWeave Playground 

  • Zero Setup :No installation or Salesforce org required to start writing and testing transformations. 
  • Real-Time Output : Transformation results are visible instantly, accelerating the development cycle. 
  • Format Flexibility :Supports testing across XML, JSON, CSV, and Apex output formats. 
  • Error Visibility:  Syntax and runtime errors are surfaced immediately, making debugging straightforward. 
  • Collaboration Friendly: Scripts can be exported and shared across teams, promoting reuse and consistency. 

  Assignments For Practice

{ 

    "first_name": "Dhanusha", 

    "last_name":  "Mediboyina", 

    "age":        24, 

    "course":     "MuleSoft Developer", 

    "city":       "Hyderabad", 

    "active":     true 

} 
  1. How do you access first_name in DataWeave? 
  1. How do you change first_name to uppercase in DataWeave? 
  1. How do you filter only first_name and last_name from this JSON? 
  1. Write a DataWeave script to combine first_name and last_name into full_name. 
  1. How do you check if age is greater than 18 in DataWeave? 
  1. How do you provide a default value if city is null? 
{ 

  "emp_id": "E101", 

  "name": { 

    "first": "Anil", 

    "last": "Reddy" 

  }, 

  "department": "IT", 

  "salary": 50000, 

  "is_active": true 

} 
  1. How do you access the employee’s first name in DataWeave? 
  1. How do you create a new field full_name by combining first and last name? 
  1. How do you increase the salary by 10% using DataWeave? 
  1. How do you filter only emp_id and department fields? 
{ 

  "order_id": "ORD123", 

  "customer_name": "Sita", 

  "items": [ 

    { 

      "product": "Laptop", 

      "price": 60000, 

      "quantity": 1 

    }, 

    { 

      "product": "Mouse", 

      "price": 500, 

      "quantity": 2 

    } 

  ], 

  "total_amount": 61000, 

  "status": "shipped" 

} 
  1. How do you access the first item’s product name? 
  1. How do you calculate total price dynamically using price * quantity for each item? 
  1. How do you transform only the items array into a new structure? 
  1. How do you filter items where price is greater than 1000? 
  1. How do you change the status to uppercase? 

Conclusion 

DataWeave in Apex stands out as a production-ready, enterprise-grade transformation engine capable of handling the full spectrum of Salesforce integration scenarios from consuming complex XML APIs to dispatching structured JSON payloads to external REST endpoints. 

Adopting DataWeave as the standard for data transformation within Salesforce development significantly reduces integration complexity, improves code maintainability, and accelerates delivery timelines  while maintaining the flexibility to integrate with virtually any system, regardless of data format or protocol. 

Leave A Comment

Your email address will not be published. Required fields are marked *

crest-partner