Thursday, June 24, 2021

Python code to deal with REST API by posting json data

Python code to deal with REST API by posting json data

Here we are taking the Cordial API as an example.

Making an API call by posting json data using Python:

To use the Cordial API, you must use their API key and also whitelist the external API of the client that is calling it.

Here we have a convenient feature that allows data exports to be directly saved to a GCS bucket.


The Code will be as follows:


        # Parameters required by Cordial API call

        url = 'https://api.cordial.io/v2/contactactivityexport'

        compress = False

        all_properties = True


        # Start datetime parameter

        start_time = execution_date.subtract(hours=1).strftime('%Y-%m-%dT%H:%M:%S.000Z')

        print("start_time api: "+start_time) # This variable is in this format: 2020-04-15T17:00:00.000Z

        

        # End datetime parameter

        end_time = execution_date.subtract(seconds=1).strftime('%Y-%m-%dT%H:%M:%S.000Z')

        print("end_time api: "+end_time) # This variable is in this format: 2020-04-15T17:00:00.000Z


        # Get the API key from Airflow connections

        api_key = BaseHook.get_connection('cordial_api_key').password


        #Send a POST request to Cordial API

        call_cordial_api = requests.post(url, 

            json={

              "name": ts_name,

              "exportType": "json",

              "destination": {

                "type": "gcs",

                "path": gcs_path,

                "gcs_bucket": gcs_bucket

              },

              "selected_timeframe_start": start_time,

              "selected_timeframe_end": end_time,

              "selected_action_names": ['open','click','optout','message-sent','message-stopped','bounce','complaint','custom'],

              "showAllProperties": all_properties,

              "compress": compress,

              "confirmEmail":"gcpnotifications@company.com"

            } , 

             auth=HTTPBasicAuth(api_key,''),

             headers={'Accept': 'application/json'}

         )

        print(call_cordial_api)

        if call_cordial_api.status_code == 200 or call_cordial_api.status_code == 201:

            pass

        else:

            raise Exception

        # Check status code for response recieved. Success Code - Response [200]. Error Code - Response [401].

        print(call_cordial_api.json()) 


 

Sample Output:

{"_id":"5f9754f","cID":"5d9cf4","ts":"2020-10-26T23:00:03+0000","mcID":"946:5f93fe:1","baseAggregate":"ot","UID":"6af0896","chnl":"email","chnl-type":"email","dur":0,"first":true,"tzo":-6,"rl":"8","email":"aecoghan@icloud.com","message_name":"SockSaleEndsToday","message_sent":"2020-10-25T11:00:00.0Z","message_tags":["Promotional"],"action":"open","time":"2020-10-26T23:00:00+0000","bmID":"946:5f93204ace295161aa12f50c:ot"}



Contact Activities:

The Contact Activities collection contain all contact-related activities such as opens, clicks, sends, and any custom actions.

Friday, June 4, 2021

Python code to deal with REST API by uploading images

Python code to deal with REST API by uploading images

Here we are taking the MulticolorEngine API as an example.

Making an API call by uploading images using Python:

The image file is sent to the MulticolorEngine API, but only one may be specified at a time and get the dominant colors as response. For each color, a similarity rank, a weight factor and a color class are returned along with the RGB values.

We can make the API call either by uploading the image files or by sending the image URLs. 

i) Python code using the image files:

import requests

from requests.auth import HTTPBasicAuth


api_url = 'https://multicolorengine.tineye.com/sandbox/rest/extract_image_colors/'

user = 'username’

password = 'password'

auth = HTTPBasicAuth(user, password)

files = {

    'images[0]': open('image1.jpg', 'rb')

}


response = requests.post(api_url, auth=auth, files=files)

json_data = response.json()

print(json_data)


images[n]: The image file from which to extract colors. Either this or urls is required, but only one may be specified at a time. This parameter can be included multiple times to specify multiple values, with n starting at 0 and increasing for each additional value.

Image limitations:

Image size: For optimal performance, uploaded images (those given by images[n] parameters) should be 600px in size in the smallest dimension. For example, 1200x800 pixels is larger than required and it will take longer to transfer this file to your MulticolorEngine server. It would be faster to resize this image to be 900x600 and then send it. Smaller images may work, and need not be scaled up.

Image format: Accepted formats are JPEG, PNG, WebP, GIF, BMP and TIFF files. Animated images are not supported.


ii).To send URL of an image file instead of the image file:

import requests

from requests.auth import HTTPBasicAuth


api_url = 'https://multicolorengine.tineye.com/sandbox/rest/extract_image_colors/'

user = 'username’

password = 'password'

auth = HTTPBasicAuth(user, password)

data={'limit': 2, 'urls[0]': 'https://content.website.com/images/image1.jpg'}


response = requests.post(api_url, auth=auth, data=data)

json_data = response.json()

print(json_data)


urls[n]: The publicly-accessible URL where the API can find the image from which to extract colors. Either this or images is required, but only one may be specified at a time. This parameter can be included multiple times to specify multiple values, with n starting at 0 and increasing for each additional value.

limit: For extracting only 2 colors from Image, set limit : 2

The maximum number of colors to be extracted when processing multiple image files, defaults to 32.


Sample output:

{

    "status": "ok",

    "error": [],

    "method": "extract_image_colors",

    "result": [

        {

            "color": [

                194,

                66,

                28

            ],

            "rank": 1,

            "class": "orange-dark,red",

            "weight": 76.37

        },

        {

            "color": [

                141,

                125,

                83

            ],

            "rank": 2,

            "class": "brown-light",

            "weight": 23.63

        }

    ]

}


Response Code: If we get the response status code as 401, then it is a failure/error. Response code 200 or 201 is for success.