尝试将 input_data 作为对 API 的 json 请求传递

Trying to pass input_data as a json request for API

下面是我的 API,我试图从包含正确的电子邮件地址、名字和姓氏的输入数据 sheet 传递信息,但是当我将其传递给 api 它没有得到解决。我在这里做错了什么

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}

您需要确保您的 JSON 有效。因此,请妥善编码。我尝试了这个并且成功了。你应该发送这个。

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

这是代码修改。

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}

如果您需要从其他地方发送一个字符串作为您的示例负载,那么您需要使用 json.loads(负载),请参阅此示例。

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

payload = json.loads(payload)
payload = json.dumps(payload)