How can we help?

Put and Post JSON (putJSON and postJSON methods)

Overview

The data stored within an externally-hosted server can be retrieved or updated by making a post/putJSON request to an API endpoint.

In this article, you'll find two examples of posting contact data to an external API. One possible use case is sending contact information to a customer service or loyalty application.

We'll describe the putJSON method in this article. The postJSON method can be used in a similar manner. The selection of the method and parameter settings depends on the implementation of the post and put methods on the external server.

First example  

Use the tabs below to view the Smarty script and the rendered output received as a result. For rendered output, the result of the request can be reviewed with the jsonPrettyPrint($data) method.

Copy and paste the code below into a message content or data job transformation script and preview the results. You can also send the message or run the data job to examine external data changes.

  • {$result = $utils->postJson('https://postman-echo.com/post', [
    "firstName" => 'John',
    "lastName" => 'Smith',
    'email' => 'jsmith@gmail.com',
    'id' => 101],
    ['headers'=>['Authorization' => 'Basic Y29yZGlhbF9zYXlzOmhlbGxv'],
    'timeout' => 6, "cacheMinutes" => 10])}
    {$utils->jsonPrettyPrint($result)}
  • [
        {
        "statusCode": 200,
        "headers": {
            "Date": [
                "Tue, 26 Apr 2022 12:22:35 GMT"
            ],
            "Content-Type": [
                "application\/json; charset=utf-8"
            ],
            "Content-Length": [
                "525"
            ],
            "Connection": [
                "keep-alive"
            ],
            "ETag": [
                "W\/\"20d-+gcDrs5d958cxHuybRpToiFbjew\""
            ],
            "Vary": [
                "Accept-Encoding"
            ],
            "set-cookie": [
                "sails.sid=s%3AI1ab0jhxbf6Hgt-elkujWi01RPVGKUC7.giirYI%2BWP2N9635pAbOIad0AbWLmCBwIERRe6eIYM80; Path=\/; HttpOnly"
            ]
        },
        "data": {
            "args": [],
            "data": {
                "firstName": "John",
                "lastName": "Smith",
                "email": "jsmith@gmail.com",
                "id": 101
            },
            "files": [],
            "form": [],
            "headers": {
                "x-forwarded-proto": "https",
                "x-forwarded-port": "443",
                "host": "postman-echo.com",
                "x-amzn-trace-id": "Root=1-6267e40b-4acf40691c406ac61c60214e",
                "content-length": "75",
                "authorization": "Basic Y29yZGlhbF9zYXlzOmhlbGxv",
                "content-type": "application\/json",
                "user-agent": "Cordial Platform"
            },
            "json": {
                "firstName": "John",
                "lastName": "Smith",
                "email": "jsmith@gmail.com",
                "id": 101
            },
            "url": "https:\/\/postman-echo.com\/post"
        },
        "error": null
    }
      ]

Second example

The following example uses the method to make a POST/PUT request to an API endpoint. For rendered output, the result of the request can be reviewed with the jsonPrettyPrint($data) method.

The system variable $contact available in the message and data job context is used in this example.

  • {$result = $utils->postJson('https://postman-echo.com/post', 
      $contact, 
      ['headers'=>['Authorization' => 'Basic Y29yZGlhbF9zYXlzOmhlbGxv'],    
    'timeout' => 6, 'cacheMinutes' => 10])}   {$utils->jsonPrettyPrint($result)}
  • {
        "statusCode": 200,
        "headers": {
            "Date": [
                "Tue, 26 Apr 2022 12:35:43 GMT"
            ],
            "Content-Type": [
                "application\/json; charset=utf-8"
            ],
            "Content-Length": [
                "1250"
            ],
            "Connection": [
                "keep-alive"
            ],
            "ETag": [
                "W\/\"4e2-jccTJQbTGWrdlwKu5W\/tXAq6oic\""
            ],
            "Vary": [
                "Accept-Encoding"
            ],
            "set-cookie": [
                "sails.sid=s%3ANbFkdEhd76Jmfwh9g6cq_JdypMwST24k.oWmMF53pgbYh5SBtavSUDhOvJa070ku3NDCytMccm6w; Path=\/; HttpOnly"
            ]
        },
        "data": {
            "args": [],
            "data": {
                "_id": "5bce15a131c96f012b74ee39",
                "channels": {
                    "email": {
                        "address": "dsmith+5bce14d13101d@cordial.com.sink.sparkpostmail.com",
                        "subscribeStatus": "subscribed"
                    }
                },
                "lists": [
                    "100k-sink"
                ],
                "lastModified": "2019-07-18T15:10:59+0000",
                "createdAt": "2018-10-22T18:23:29+0000",
                "name": "Lucya",
                "mdtLastSent": {
                    "5c99a3b610986b7e3ce5a4b8": {
                        "sec": 1556892890,
                        "usec": 0
                    }
                },
                "age": 1,
                "cID": "5bce15a131c96f012b74ee39",
                "id": "5bce15a131c96f012b74ee39"
            },
            "files": [],
            "form": [],
            "headers": {
                "x-forwarded-proto": "https",
                "x-forwarded-port": "443",
                "host": "postman-echo.com",
                "x-amzn-trace-id": "Root=1-6267e71f-66aa6700217d097f20dbc636",
                "content-length": "437",
                "authorization": "Basic Y29yZGlhbF9zYXlzOmhlbGxv",
                "content-type": "application\/json",
                "user-agent": "Cordial Platform"
            },
            "json": {
                "_id": "5bce15a131c96f012b74ee39",
                "channels": {
                    "email": {
                        "address": "dsmith+5bce14d13101d@cordial.com.sink.sparkpostmail.com",
                        "subscribeStatus": "subscribed"
                    }
                },
                "lists": [
                    "100k-sink"
                ],
                "lastModified": "2019-07-18T15:10:59+0000",
                "createdAt": "2018-10-22T18:23:29+0000",
                "name": "Lucya",
                "mdtLastSent": {
                    "5c99a3b610986b7e3ce5a4b8": {
                        "sec": 1556892890,
                        "usec": 0
                    }
                },
                "age": 1,
                "cID": "5bce15a131c96f012b74ee39",
                "id": "5bce15a131c96f012b74ee39"
            },
            "url": "https:\/\/postman-echo.com\/post"
        },
        "error": null
    }

Parameters

Parameter

Description

Required

Expected

Default

url

URL for the externally hosted endpoint

required

valid URL

NA

payload

payload for the request containing the data update

required

an array of key/values pairs

NA

options

Allows for the configuration of options such as HTTP request headers or maximum wait time.

optional

an array of key/values pairs

[]

Set the URL 

For the purpose of this example, we'll use the server accessible by the link below. 

In the examples above, we assume the contact data with firstName, lastName, email, and id properties are stored at this same location.

Set the payload 

Payload is a data set to be uploaded to the external server. It is an array of key/value pairs that are supported by external server API.

In the following example, the array is defined within the method. 

[
"firstName" => "John",
"lastName" => "Smith",
"email" => "jsmith@gmail.com",
"id" => 101]

In this next example, the system variable $contact was used as the payload parameter.

['contact_object' => $contact] 

Using this approach, you should ensure that the data properties expected by the external server are available in the contact object.

Set options 

This parameter allows for the configuration of additional processing options. Within the options you can set headers, timeout, and cache minutes.

Setting HTTP request headers pass additional information to server with a request. It is an array of header names and values. 

Headers can be used for authorization, as in the following example.

['headers'=>['Authorization' => 'Basic <base64 encoded username:password>']]

Other headers can be passed as supported by the target API. 

Set timeout

Set the request timeout in seconds. When the timeout is expired, the request will be considered failed. The default value is 15 seconds.

['timeout' => 1]

Set cacheMinutes

Within the defined cacheMinutes period, the response for the same requests will be cached across different renderings. The default value is 0.

['cacheMinutes' => 10]

Response processing

The result of the request processing returned in the server response can be reviewed with the help of the jsonPrettyPrint($data) method. It is an array of the following key/value pairs.

'statusCode' => int
'headers' => array
'data' => string|array
'error'=>string|null

Allowed status codes

Allowed status codes of response codes that will be treated as successful are [200, 404, 201, 204]. The response can be processed in the script.

Based on the response status, you can update the contact to form the list of contacts stored on an external server, which is shown in the following example.

   {if $result.status == 200}
       {$utils->updateContact(['Stored_externaly'=>true], true, false)}
 {/if}

Comments

0 comments

Please sign in to leave a comment.