Search code examples
pythonpandaspython-requestsapi-design

How to iterate rows of dataframe in Content-Type: application/x-www-form-urlencoded format into API POST request?


I have a dataframe that looks like this:

email        p[1]:
[email protected]       1
[email protected]       2 

the p[1] field is the list ID.

How do I pass rows of this dataframe one at a time into the a API post request in the Content-Type: application/x-www-form-urlencoded format?

Without a dataframe when I try this code it works:

headers = {
    'content-type': 'application/x-www-form-urlencoded',
}

params = {
    'email': '[email protected]',
   ' p[1]': '1',
}

url = 'https://URL/admin/api.php?api_action=contact_add&api_output=json&api_key=123ABC' 
resp = requests.post(url, data=params, headers=headers)

How do I pass each row of the dataframe and how do I convert the dataframe format into the params equalivent format?

This api does not take bulk uploads. More information can be found here about the API. https://www.activecampaign.com/api/example.php?call=contact_add

Thank you in advance.


Solution

  • If you want to do this one at a time, you want DataFrame.iterrows

    import pandas as pd
    
    df = pd.DataFrame({'email': ['[email protected]', '[email protected]'], 'p[1]': [1,2]})
    
    for index, row in df.iterrows():
        params = {'email': row.email, 'p[1]': row['p[1]']}
        print(params)
    
    {'email': '[email protected]', 'p[1]': 1}
    {'email': '[email protected]', 'p[1]': 2}
    

    You can then pass the params to whatever you want one at a time inside of the loop.