Search code examples
zapier

Trying to pass input_data as a json request for API


Below is my API, I am trying to pass the information from an input data sheet that contains proper emailaddress, firstname, and lastname, however when i am passing that to api it doesn't get resolved. what am I doing wrong here

import requests

url = "https://api.ZZZ.us/v2/users"

payload = "{\r\n \"action\": \"create\",\r\n \"user_info\": {\r\n
\"email\": \"input_data['emailaddress']\",\r\n \"type\": 1,\r\n \"first_name\": \"input_data['firstname']\",\r\n \"last_name\": \"input_data['lastname']\"\r\n }\r\n}" headers = { 'Accept': "application/json, application/xml", 'Content-Type': "application/json", 'Authorization': "Bearer XXXXX", 'cache-control': "no-cache", 'Postman-Token': "ab32d014-97fb-499e-8adf-c1baf49871e2" }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text) output = {'id': 1333121, 'response': response.text}


Solution

  • you need to make sure your JSON is valid. For this reason please encode it well. I tried this and worked out. you should be sending this.

    {
        "action": "create",
        "user_info": {
            "email": "mymail@gmail.com",
            "first_name": "mike",
            "last_name": "tyson"
        }
    }
    

    This is the code modifications.

    import requests
    import json
    
    url = "https://enzi2vbg2aau9.x.pipedream.net/"
    
    input_data = ["mymail@gmail.com", 'mike', 'tyson']
    
    payload = json.dumps({
      "action": "create",
      "user_info": {
        "email": input_data[0],
        "first_name": input_data[1],
        "last_name": input_data[2]
      }
    })
    
    headers = { 
      'Accept': "application/json, application/xml", 
      'Content-Type': "application/json", 
      'Authorization': "Bearer XXXXX", 
      'cache-control': "no-cache", 
      'Postman-Token': "ab32d014-97fb-499e-8adf-c1baf49871e2" 
      }
    
    response = requests.request("POST", url, data=payload, headers=headers)
    
    print(response.text) # output = {'id': 1333121, 'response': response.text}
    

    if you need to send a string from somewhere else that comes as your example payload then you need to use json.loads(payload) please see this example.

    payload = '''{
        "action": "create",
        "user_info": {
            "email": "mymail@gmail.com",
            "first_name": "mike",
            "last_name": "tyson"
        }
    }'''
    
    payload = json.loads(payload)
    payload = json.dumps(payload)