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 = ''

        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 =, 


              "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,


            } , 


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



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



            raise Exception

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



Sample Output:


Contact Activities:

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