You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python发送JSON数据至API遭拒,提示ContactId缺失求助

Fix: "ContactId is Required" Error When Sending JSON to API

Problem

As a Python beginner working with JSON operations, I'm stuck on an issue: when fetching a list of ContactIds from a database and sending them to an API via a PUT request, I keep getting a "ContactId is Required." error response—even though my printed JSON data looks correct.

Code Snippet

rpt_cursor = rpt_conn.cursor()
sql="""SELECT `ContactID` AS 'ContactId' FROM `BWG_reports`.`bounce_log_dummy`;"""
rpt_cursor.execute(sql)
row_headers=[x[0] for x in rpt_cursor.description] # Extract row headers
row_values= rpt_cursor.fetchall()
json_data=[]
for result in row_values:
    json_data.append(dict(zip(row_headers,result)))
results_to_load = json.dumps(json_data)
print(results_to_load) # Output: [{"ContactId": 9}, {"ContactId": 274556}]
headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}
targetlist = '302' # For PUT request "Batch add contacts to list"
api_request_url = 'https://api2.xyz.com/api/list/' + str(targetlist) +'/contactid/Api_Key/' + bwg_apikey
print(api_request_url) # Output: https://api2.xyz.com/api/list/302/contactid/Api_Key/#####
response = requests.put(api_request_url, headers=headers, data=results_to_load)
print(response) # Output: <Response [200]>
print(response.content) # Output: b'{"status":"error","Message":"ContactId is Required."}'
rpt_conn.commit()
rpt_cursor.close()

Additional Context

  • The JSON data I'm sending: [{"ContactId": 9}, {"ContactId": 274556}]
  • API documentation requires the request body format: [ { "ContactId": "string" } ]
  • When manually sending data with string-type ContactIds (e.g., [ { "ContactId": "9" }, { "ContactId": "274556" } ]), the API call succeeds.
  • I initially suspected issues with json.dumps/json.load, thinking maybe I was generating a string that looks like a dictionary instead of valid JSON.

Solution

Turned out it was a simple mistake: I needed to initialize results_to_load as an empty list ([]) before executing results_to_load = json.dumps(json_data). After making this adjustment, the API call works correctly.


内容的提问来源于stack exchange,提问作者ManOAction

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:07:36