2 years ago
#22992
William
Iterating through multiple API payloads
Background:
I have a dictionary
my_dict
containing c.3000 rows of key/value pairs -
Extract:{'id_and_external_id_sf': {11028697: '0013h000014kIGMAA2', 11028699: '0013h000014kISXAA2', 10264791: '0013h00000ZBqoYAAT'}}
I also have a payload, stored in
data
, which I will need to inc. in API calls for each key/pair value inmy_dict
Specifically, I need to iterate throughmy_dict
and for every key/pair value, need to mapid
andexternal_id_sf
to their respective places in the payload.
Payload:
data = """
{
"data": {
"id": "<KEY FROM DICT>",
"type": "entities",
"attributes": {
"external_id_sf": "<VALUE FROM DICT>"
}
}
}
"""
- Finally, when calling the API, the
PATCH
url needs to be suffixed with theid
frommy_dict
. E.g., the payload that contains11028697: '0013h000014kIGMAA2'
will have a URL ofhttps://myfirm.vendor.com/api/v1/entities/11028697
My code so far:
Function that saves key-value pairs in my_dict
from .xlsx file:
# Saving key-value pairs from a .xlsx file
def excel_to_dict():
my_dict = pd.read_excel('entities.xlsx', index_col=0).to_dict()
return my_dict
excel_to_dict()
Function that saves all id
from .xlsx file to list, so API urls can be constructed:
def ids_list():
df = pd.read_excel('entities.xlsx')
ids_list = df['entities'].tolist()
return ids_list
Function that creates API PATCH
call URLs, using id
s from ids_list()
def url_constructor():
ids_list = excel_to_list()
str = "https://firm.vendor.com/api/v1/entities/{}"
url_list = []
for entity in ids_list:
url = str.format(entity)
url_list.append(url)
return url_list
url_constructor()
Function that contains payload (data
) template, which needs to be inc. in the API calls for each respective id
and external_id_sf
:
def payload_data():
data = """
{
"data": {
"id": "11028697",
"type": "entities",
"attributes": {
"external_id_sf": "0013h000014kIGMAA2"
}
}
}
"""
return data
Where I need help:
I am struggling to work out how I can bring these segments of code together so I can the following is achieved -
- Make an API call for each url in
url_list
- Whilst calling a url, inc. the payload with the same
id
and it's correspondingexternal_id_sf
frommy_dict
, to ensure the correct payload is sent for each API call. I'm not sure if you can use curly brackets, for the purpose of data mapping, as I did in theurl_constructor
function.
I appreciate this is a lot of information, so any suggestions would be warmly received.
python
api
payload
0 Answers
Your Answer