I'm new to Python. Trying to automate some painful API calls using the Python requests
module. Getting pretty close, but can't figure out how to pass lists of timestamps as request parameters
Example: Generate list of lastModified
timestamps
import datetime
from datetime import datetime, timedelta
earliest_ts_str = '2020-10-01T15:00:00Z'
earliest_ts_obj = datetime.strptime(earliest_ts_str, timestamp_format)
#bottom_ts_obj = earliest_ts_obj.replace(second=0, microsecond=0, minute=0)
latest_ts_str = '2020-10-01T23:00:00Z'
latest_ts_obj = datetime.strptime(latest_ts_str, timestamp_format)
ts_raw = []
while earliest_ts_obj < latest_ts_obj:
ts_raw.append(earliest_ts_obj)
earliest_ts_obj += timedelta(hours=1)
ts_raw.append(latest_ts_obj)
ts_formatted = [d.strftime('%Y-%m-%dT%H:%M:%SZ') for d in ts_raw]
ts_formatted
Results:
['2020-10-01T15:00:00Z',
'2020-10-01T16:00:00Z',
'2020-10-01T17:00:00Z',
'2020-10-01T18:00:00Z',
'2020-10-01T19:00:00Z',
'2020-10-01T20:00:00Z',
'2020-10-01T21:00:00Z',
'2020-10-01T22:00:00Z',
'2020-10-01T23:00:00Z']
Example 2: Create the request
call
- Here is (obviously) where my problem is. I tried to flesh out a function to handle it, but its not even close!
- How do I pass the first timestamp in the list as the
lastModifiedStart
parameter? AND - Pass the second timestamp in the list as the
lastModifiedEnd
parameter? - Then so on until all timestamps have been tried?
import requests
method = 'get'
base_url = 'https://sandbox-api.com/'
api_type = 'items'
api_version = '/v1/'
api_path = api_type + api_version
api_key = 'myKey'
full_url = base_url + api_path
def make_historic_calls(last_mod_start, last_mod_end):
last_mod_start = for ts in ts_formatted: ts
last_mod_end = for ts in ts_formatted: ts
parameters = {'api_key':api_key, 'lastModifiedStart': last_mod_start, 'lastModifiedEnd': last_mod_end}
auth_header = {'Authorization': 'Basic <base64EncodedStringHere>'}
resp_raw = requests.request(method, full_url, headers=auth_header, params=parameters)
resp_processed = json.loads(resp_raw.content)
resp_pretty = json.dumps(resp_processed, indent=2, sort_keys=True)
return print(pretty)
test = make_historic_calls(ts_formatted, ts_formatted)
I know this isn't an easy solve (its taken me days and days to get this far), but any guidance on how to tackle this would be appreciated.
Thank you
EDIT 1: This adjusted function works great!
def make_historic_calls(ts_formatted):
for last_mod_start, last_mod_end in zip(ts_formatted, ts_formatted[1:]):
parameters = {'api_key':api_key, 'lastModifiedStart': last_mod_start, 'lastModifiedEnd': last_mod_end}
auth_header = {'Authorization': 'Basic <base64EncodedString>'}
resp_raw = requests.request(method, full_url, headers=auth_header, params=parameters)
print(f'{resp_raw.url} Status Code: {str(resp_raw.status_code)}')
return print(resp_raw)
test = make_historic_calls(ts_formatted)