首页 > 解决方案 > 我的 Python 代码中是否缺少任何东西来发出 POST API 请求?

问题描述

我正在尝试使用 Python 代码向供应商站点发出 POST API 请求。我正在使用 Anaconda 中的 Jupyter Notebooks 来完成这项任务。我也在 Python 中使用 requests 和 json 库。假设此请求在供应商应用程序中创建地理区域。到目前为止,我已经对供应商建议的代码进行了一些小调整,在多台计算机/网络上测试了代码,并尝试将 API 密钥放在 PARAMS 字典中,而不是将 API 密钥放在 URL 中(见下面的代码) . 经过我所有的尝试,我收到了 400 或 401 状态代码,但我不确定我哪里出错了。为了屏蔽敏感信息,我在下面的代码中输入了 X。如果有人能指出我哪里出错了,我将不胜感激。

url2 = 'https://insight.streetlightdata.com/api/v2/zone_sets?key=XXX'

headers = {'Content-Type': 'application/json'}

# tried to test the code by using the API key in dictionary PARAMS, instead of URL
# auth = 'XXX'
# PARAMS = {'key':auth}

data ={}
data["insight_login_email"] = "XXX@X.X.X"
data["geom_type"] = "polygon"
data["zones"] = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "id": 1, "name": "Mission", "is_pass": 0, "direction": "null" }, 
 "geometry": { "type": "MultiPolygon", "coordinates": [ [ [         
    [-73.93549919128418, 40.758830406665325],[-73.93404006958008,40.756554888619675],
    [-73.92983436584473,40.75694498295937],[-73.9313793182373,40.75967557924376],
    [-73.93549919128418,40.758830406665325]] ] ] } },
{ "type": "Feature", "properties": { "id": 2, "name": "Financial District", "is_pass": 0, "direction": "null" }, 
 "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [-73.90829086303711,40.75687996739503],
    [-73.90803337097168,40.75330401343781],[-73.90554428100586,40.753499070431374],
    [-73.90829086303711,40.75687996739503]] ] ] } }
]
}

r3 = requests.post(url2, json=data, headers=headers)
r3.status_code

# used the below in the parenthesis of r3 line when testing API key in dictionary, instead of URL
#  params=PARAMS,```

标签: pythonapipostpython-requests

解决方案


推荐阅读