Using data from API in subsequent API calls

Viewed 57

I should preface this with I am not a programmer and most of this code was not written by me. I unfortunately have a need and am trying to hack my way through this.

What I am trying to do is chain a few API calls together to ultimately get a list of IPs. What this script does is queries the API and pulls (and prints) a list of device IDs. The device IDs look like this:

akdjlfijoaidjfod
g9jkidfjlskdjf44
3jdhfj4hf9dfiiu4

The device IDs then need to be passed as a parameter in the next API call like this:

https://api.example.com/devices/entities/devices/v1?ids=akdjlfijoaidjfod&ids=g9jkidfjlskdjf44&ids=3jdhfj4hf9dfiiu4 and so on.

I dont know where to begin. Instead of printing the asset ids, I assume they should be stored as a parameter (or variable) and then appended to the URL. I tried doing that with "ID_LIST" but that didnt seem to work. Can you guys point me in the right direction?

import requests
import json

# Define API REST paths
BASE_URL = "https://api.example.com/"
OAUTH_URL_PART = "oauth2/token"
DEVICE_SEARCH = "devices/queries/devices/v1"
DEVICE_DETAILS = "devices/entities/devices/v1"

# Empty auth token to hold value for subsequent request
auth_Token = ""

# Section 1 - Authenticate to Example OAUTH

# Build a dictionary to hold the headers
headers = {
    'Content-type': 'application/x-www-form-urlencoded',
    'accept': 'application/json'
}

# Build a dictionary to holds the authentication data to be posted to get a token
auth_creds = {}
auth_creds['client_id'] = "<client_id>"
auth_creds['client_secret'] = "<client_secret>"
auth_creds['grant_type'] = "client_credentials"

# Call the API to get a Authentication token - NOTE the authentication creds
print("Requesting token from " + BASE_URL + OAUTH_URL_PART)
auth_response = requests.post(BASE_URL + OAUTH_URL_PART,data=auth_creds, headers=headers)

# Check if successful
if auth_response.status_code != 201:
    # Output debug information
    print("\n Return Code: " + str(auth_response.status_code) + " " + auth_response.reason)
    print("Path: " + auth_response.request.path_url)
    print("Headers: ")
    print(auth_response.request.headers)
    print("Body: " + auth_response.request.body)
    print("\n")
    print("Trace_ID: " + auth_response.json()['meta']['trace_id'])
else:

    # Section 2 - Capture OAUTH token and store in headers for later use

    print("Token Created")
    # Capture the auth token for reuse in subsequent calls, by pulling it from the response
    # Note this token can be reused multiple times until it expires after 30 mins
    auth_Token = auth_response.json()['access_token']

    headers = {
        'authorization':'bearer ' + auth_Token,
        'accept': 'application/json'
    }

# Section 3 - Reuse authentication token to call other Example OAUTH2 APIs

# Build parameter dictionary
call_params = {}
call_params['offset'] ="" # Non-mandatory param
call_params['limit'] ="5000" # The number of results
call_params['sort'] ="" #
call_params['filter'] ="" # To exclude devices

# Call devices API
print("Searching Asset ID by getting from " + BASE_URL + DEVICE_SEARCH)
DEVICE_search_response = requests.get(BASE_URL + DEVICE_SEARCH,params=call_params,headers=headers)
#DEVICE_DETAILS_response = request.get(BASE_URL + DEVICE_DETAILS,headers=headers)

# Check for errors
if DEVICE_search_response.status_code != 200:
    # Output debug information
    print("\n Return Code: " + str(DEVICE_search_response.status_code) + " " + DEVICE_search_response.reason)
    print("Path: " + DEVICE_search_response.request.path_url)
    print("Headers: ")
    print(DEVICE_search_response.request.headers)
    print("Body: " + DEVICE_search_response.request.body)
    print("\n")
    print("Trace_ID: " + DEVICE_search_response.json()['meta']['trace_id'])
else:
    # Iterate the results and print
    result = DEVICE_search_response.json()
    print("DEVICE found on " + str(len(result['resources'])) + " the following device id:")
    for devices in result['resources']:
        print(devices)

###########Part that is not working###########

DEVICE_DETAILS_response = requests.get(BASE_URL + DEVICE_DETAILS,headers=headers)
#ID_LIST = str(len(result['resources']).replace(",", "&ids=")
if DEVICE_DETAILS_response.status_code != 200:
    # Output debug information
    print("\n Return Code: " + str(DEVICE_DETAILS_response.status_code) + " " + DEVICE_DETAILS_response.reason)
    print("Path: " + DEVICE_DETAILS_response.request.path_url)
    print("Headers: ")
    print(DEVICE_DETAILS_response.request.headers)
    print("Body: " + DEVICE_DETAILS_response.request.body)
    print("\n")
    print("Trace_ID: " + DEVICE_DETAILS_response.json()['meta']['trace_id'])
else:
    result = DEVICE_DETAILS_response.json()
    print("Device Details Found")
    for details in result['resources']:
        print(details)
1 Answers

Hi to convert the strings in result['resources']:

['akdjlfijoaidjfod',
'g9jkidfjlskdjf44',
'3jdhfj4hf9dfiiu4']

to : https://api.example.com/devices/entities/devices/v1?ids=akdjlfijoaidjfod&ids=g9jkidfjlskdjf44&ids=3jdhfj4hf9dfiiu4

try this funciton:

def get_modified_url(mylist, myurl):
    url = myurl + '?'
    for idx, b in enumerate(mylist):  # enumerate list to get index and element in  the list
        if idx > 0:
            url += '&ids=' + b # append &ids= to url if not first device id
        else:
            url += 'ids=' + b  # append ids= to url if first device id

    return url

print(get_modified_url(result['resources'], BASE_URL + DEVICE_DETAILS ))

full code would be:

def get_modified_url(mylist, myurl):
    url = myurl + '?'
    for idx, b in enumerate(mylist):  # enumerate list to get index and element in  the list
        if idx > 0:
            url += '&ids=' + b # append &ids= to url if not first device id
        else:
            url += 'ids=' + b  # append ids= to url if first device id

    return url

device_list = []

DEVICE_search_response = requests.get(BASE_URL + DEVICE_SEARCH,params=call_params,headers=headers)

# Check for errors
if DEVICE_search_response.status_code != 200:
    # Output debug information
    print("\n Return Code: " + str(DEVICE_search_response.status_code) + " " + DEVICE_search_response.reason)
    print("Path: " + DEVICE_search_response.request.path_url)
    print("Headers: ")
    print(DEVICE_search_response.request.headers)
    print("Body: " + DEVICE_search_response.request.body)
    print("\n")
    print("Trace_ID: " + DEVICE_search_response.json()['meta']['trace_id'])
else:
    # Iterate the results and print
    result = DEVICE_search_response.json()
    print("DEVICE found on " + str(len(result['resources'])) + " the following device id:")
    for devices in result['resources']:
        print(devices)
        device_list.append(devices)


new_url = get_modified_url(device_list, BASE_URL + DEVICE_DETAILS )
DEVICE_DETAILS_response = requests.get(new_url, headers=headers)

if DEVICE_DETAILS_response.status_code != 200:
    # Output debug information
    print("\n Return Code: " + str(DEVICE_DETAILS_response.status_code) + " " + DEVICE_DETAILS_response.reason)
    print("Path: " + DEVICE_DETAILS_response.request.path_url)
    print("Headers: ")
    print(DEVICE_DETAILS_response.request.headers)
    print("Body: " + DEVICE_DETAILS_response.request.body)
    print("\n")
    print("Trace_ID: " + DEVICE_DETAILS_response.json()['meta']['trace_id'])
else:
    result = DEVICE_DETAILS_response.json()
    print("Device Details Found")
    for details in result['resources']:
        print(details)
Related