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.