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/
compress = False
all_properties = True
# Start datetime parameter
start_time = execution_date.subtract(hours=
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(
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('
#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','
"showAllProperties": all_properties,
"compress": compress,
"confirmEmail":"gcpnotificatio
} ,
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":"
Contact Activities:
The Contact Activities collection contain all contact-related activities such as opens, clicks, sends, and any custom actions.
0 Comments