Resolving Challenges: Tackling PUT, PATCH, and DELETE Operations in REST API

Resolving Challenges
Home Page

Resolving Challenges: Tackling PUT, PATCH, and DELETE Operations in REST API Marketing Cloud Integration

In this article, we delve into the common challenges encountered while implementing PUT, PATCH, and DELETE operations in the Marketing Cloud REST API and provide effective solutions to overcome them. We explore the complexities of updating and modifying resources within the Marketing Cloud ecosystem, handling partial updates, managing data consistency, dealing with authorization and authentication issues specific to Marketing Cloud, and ensuring proper error handling. By addressing these challenges, developers can optimize their interactions with the Marketing Cloud REST API, enabling seamless integration and efficient data management within the Marketing Cloud platform.

In addition to tackling the challenges of PUT, PATCH, and DELETE operations, another aspect to consider is the limited support for these operations within the core library of Marketing Cloud's REST API. The core library primarily focuses on providing comprehensive support for POST and GET operations, which are widely used and crucial for data interaction within the Marketing Cloud ecosystem.

When working with the core library, developers need to align their implementation strategies around these supported operations. This means that only POST and GET requests are considered valid and supported within the context of the core library. Any attempts to use PUT, PATCH, or DELETE operations may result in errors or unexpected behavior.

It's important for developers to familiarize themselves with the documentation and guidelines provided by Marketing Cloud to understand the specific use cases and best practices for utilizing POST and GET operations effectively. By doing so, developers can maximize the benefits of the core library and seamlessly integrate their applications with Marketing Cloud, enabling robust marketing automation and personalized customer experiences.

Leveraging Platform Functions for SSJS in Marketing Cloud

Similar to AMPscript, platform functions for Server-Side JavaScript (SSJS) in Marketing Cloud provide marketers and developers with a robust toolkit to enhance marketing automation and personalization. These functions offer a familiar programming language that allows for data manipulation, custom business logic, integration with external systems, and seamless execution of dynamic campaigns.

By leveraging platform functions available within Marketing Cloud, developers can successfully accomplish these operations that were not directly supported by the core library. The platform functions offer a more extensive set of capabilities, allowing for resource updates, modifications, and deletions using the appropriate HTTP methods. By utilizing these platform functions, developers can seamlessly integrate and interact with the Marketing Cloud REST API, unlocking the full potential of their marketing automation and data management workflows.

Exploring Content Syndication Functions in Marketing Cloud

Beyond the standard HTTPGet() and HTTPPost() objects. These functions empower marketers to specify content types, utilize different HTTP methods, and achieve greater customization and integration possibilities

Content Syndication Objects :

In this discussion, we will focus specifically on Script.Util.HttpRequest, a powerful platform function within Marketing Cloud that enables robust HTTP requests and content syndication capabilities. By utilizing Script.Util.HttpRequest, marketers can efficiently retrieve, send, and manage HTTP-based content, leveraging various HTTP methods, headers, and parameters. This function provides a comprehensive solution for content syndication, allowing marketers to synchronize and distribute their marketing content seamlessly across multiple channels.

Script.Util.HttpRequest


Syntax

Script.Util.HttpRequest(1)


Methods
  • setHeader() - Name and value pairs of headers sent when performing the GET request, which disables content caching
  • removeHeader() - String value indicating header to remove from collection sent with request
  • clearHeader() - String value indicating removal of all custom headers set for the request
  • send() - Perform a send of the request to the website and returns a response data object

Example

This sample code performs a PATCH request with a "Authorization" header and "Bearer AccessToken". The function then wreturn the response after the send() request.

                                        
<script runat="server">
  function InvokeRESTAPIPATCH(installPackageConfig,accessTokenConfig,methodAPIConfig,payload,key)
  {
   
    // Call AccessToken function to retrieve for Access Token
    var accessTokenResult=AccessToken(installPackageConfig,accessTokenConfig);
    var statusCode = accessTokenResult["StatusCode"];
    var response = accessTokenResult["Response"][0];
    var accessToken = Platform.Function.ParseJSON(response).access_token;
    var tokenType = Platform.Function.ParseJSON(response).token_type;
    //Write("Access Token :" + tokenType + " " +accessToken +"\n");
    
    var httpHeadersName=["Authorization"];
    var httpHeaderValues=[tokenType + " " +accessToken];
    
    // Call DataExtensionRowsRetrieve function to retrieve for API Config
    var APIConfiDE=DataExtensionRowsRetrieve(installPackageConfig);
    var restAPI=APIConfiDE[0]["RESTAPI"];
    
    // Call DataExtensionRowsRetrieve function to retrieve for APIMethod Config
    var APIMethodDE=DataExtensionRowsRetrieve(methodAPIConfig);
    var httpProtocol = APIMethodDE[0]["HttpProtocol"];
    var methodURL = APIMethodDE[0]["MethodURL"];
    var methodURL_1 = APIMethodDE[0]["MethodURL_1"];
    var methodURL_2 = APIMethodDE[0]["MethodURL_2"];
    var contentType = "application/json;charset=UTF-8";
    if(methodURL_1)
    {
      var URL=restAPI+methodURL+methodURL_1.replace("{configKey}",key);
    }
    else
    {
      var URL=restAPI+methodURL;
    }
    //Write('\n' + URL + '\n' );
    
    var postPayload=payload;
    //Write('\n' + Stringify(postPayload) + '\n'  );

    var request=new Script.Util.HttpRequest(URL);
    request.emptyContentHandling = 0;
    request.retries = 2;
    request.continueOnError = true;
    request.setHeader("Authorization",tokenType + " " +accessToken);
    request.method = "PATCH";
    request.contentType = "application/json; charset=utf-8";
    request.postData = Stringify(postPayload);
    var httpResponse = request.send();
    
    return httpResponse;
    }
</script>
                                        
                                    
Full Code : If you are new to my blog please do read my previous blogs on SSJS to comprehend fully
                                    
<script runat="server" >
  Platform.Load("core", "1");
  var contentDE = Platform.Function.ContentBlockByKey("DataExtensionRowsRetrieve");
  var contentSimpleOperators = Platform.Function.ContentBlockByKey("SimpleOperators");
  var contentAccessToken = Platform.Function.ContentBlockByKey("AccessToken");
  var contentRESTAPIPOST = Platform.Function.ContentBlockByKey("InvokeRESTAPIPATCH");
  var contentDefineDataExtensionRetrieve = Platform.Function.ContentBlockByKey("DefineDataExtensionRetrieve");
  try{
    // Define properties for API Config
    var installPackageConfig=DefineDataExtensionRetrieve("APIConfig","Equals","TransactionalAPI","InstallPackages");
    // Define properties for Access token
    var accessTokenConfig=DefineDataExtensionRetrieve("MethodName","Equals","Request SFMC Token","APIMethod");
    // Define properties for REST API Method call
    var methodAPIConfig=DefineDataExtensionRetrieve("MethodName","Equals","Update Contacts","APIMethod");
    var payload={
      "contactKey": "Shashi1",
      "attributeSets": [
        {
          "name": "Email Addresses",
          "items": [
            {
              "values": [
                {
                  "name": "Email Address",
                  "value": "b2.shashi+updated@gmail.com"
                }
                ,
                {
                  "name": "HTML Enabled",
                  "value": true
                }
              ]
            }
          ]
        }
        ,
        {
          "name": "Email Demographics",
          "items": [
            {
              "values": [
                {
                  "name": "First Name",
                  "value": "Sasee"
                }
              ]
            }
          ]
        }
      ]
    }
    var key="";
    var restResponse=InvokeRESTAPIPATCH(installPackageConfig,accessTokenConfig,methodAPIConfig,payload,key);
    Write((String(restResponse.content)) + '\n');
    //Write((String(restResponse.headers["returnHeader"])) + '\n');
  }
  catch(ex)
  {
    var APIExceptionDE = DataExtension.Init("APIException");
    APIExceptionDE.Rows.Add(
      {
        Message:ex.message
        ,Description:ex.description
        ,InnerException:ex.jintException
        ,FunctionName:"Main Block"
      }
    );
    Write(ex.message + '\n');
    Write(ex.description + '\n');
    Write(ex.jintException + '\n');
  }
</script>
                                    
                                


Comments


Knowledge Article

Most Viewed

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

Popular Posts

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Journey Builder REST API Documentation

Preference Center Demystified

SEND LOG EANBLEMENT

Share with Friends

Disclaimer:

The information provided on this technical blog is for general informational purposes only. As a SFMC (Salesforce Marketing Cloud) Technical Architect, I strive to offer accurate and up-to-date content related to SFMC and its associated technologies. However, please note that technology is constantly evolving, and the information provided may become outdated or inaccurate over time.

The content published on this blog represents my personal views and experiences as a SFMC Technical Architect and does not necessarily reflect the official views or opinions of any organization or employer I may be affiliated with.

While I make every effort to ensure the accuracy and reliability of the information presented, I cannot guarantee its completeness, suitability, or applicability to your specific circumstances. Therefore, it is essential to verify any information provided and make your own independent assessments or seek professional advice if needed.

Furthermore, any actions taken based on the information provided on this blog are at your own risk. I shall not be held liable for any damages, losses, or inconveniences arising from the use of the information presented here.

Please keep in mind that SFMC and its associated technologies are complex and require technical expertise for proper implementation and management. It is recommended to consult with qualified professionals or official SFMC documentation for comprehensive guidance.

Finally, please note that any product or company names mentioned on this blog are trademarks or registered trademarks of their respective owners. The mention of these trademarks or registered trademarks does not imply any endorsement or affiliation with the blog.

By accessing and using this blog, you agree to the terms of this disclaimer. If you do not agree with any part of this disclaimer, please refrain from using this blog.