英文:
error 400 when I try to use an API (Python)
问题
我正在尝试使用Société du Métro de Montréal (STM)的API,这是一个交通GTFS传输API。
当我尝试以下Python代码时,我收到了400错误代码("请求过多")。
我想知道是否有人正在使用交通API,并可以给我一些关于我做错了什么的提示。
import requests
api_key = "API-KEY-FROM-DEVELOPER-ACCOUNT"
api_url = f"https://api.stm.info/pub/od/gtfs-rt/ic/v2/vehiclePositions"
# 准备带有API密钥的请求头
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
# 发送HTTP GET请求到API端点
response = requests.get(api_url, headers=headers)
# 如果你得到200作为响应...一切正常
print("response.status_code", response.status_code)
# 检查请求是否成功(状态码为200)
if response.status_code == 200:
try:
# 解析JSON响应
data = response.json()
# 根据需要处理和使用检索到的数据
print(data)
except ValueError as e:
print("解析JSON时出错:", e)
print("响应内容:", response.text)
else:
# 处理未成功的请求
print(f"错误: {response.status_code}")
我期望得到一个200的响应:
print("response.status_code", response.status_code)
稍后更新
实际上问题出在身份验证方法上。我用下面的头部替换了原来的头部,它给了我200的响应,确认我能够连接到API。
= 问题已解决
头部如下:
headers = {
"apiKey": api_key,
"Content-Type": "application/json"
}
感谢所有尝试帮助的人... 还有非常感谢ChatGPT!!!
英文:
I am trying to use the API from Société du Métro de Montréal (STM), a transportation GTFS transportation API.
I get error code 400 ("Too many requests") when trying the Python code below. I wonder if anyone is working with transportation APIs and can give me some hints on what I did wrong.
import requests
api_key = "API-KEY-FROM-DEVELOPER-ACCOUNT"
api_url = f"https://api.stm.info/pub/od/gtfs-rt/ic/v2/vehiclePositions"
# Prepare the request headers with the API key
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
# Send the HTTP GET request to the API endpoint
response = requests.get(api_url, headers=headers)
# if you get 200 as response... everything ok
print("response.status_code",response.status_code)
# Check if the request was successful (status code 200)
if response.status_code == 200:
try:
# Parse the JSON response
data = response.json()
# Process and use the retrieved data as needed
print(data)
except ValueError as e:
print("Error parsing JSON:", e)
print("Response content:", response.text)
else:
# Handle unsuccessful request
print(f"Error: {response.status_code}")
I expected a response 200 for:
print("response.status_code",response.status_code)
LATER UPDATE
Actually the issue was in the authentication method. I replaced the headers by the ones below and it gave me the response 200, confirming that I was able to connect to the API.
= issue closed
headers = {
"apiKey":api_key,
"Content-Type": "application/json"
}
Thanks to all who tried to help... and thanks a lot to ChatGPT !!!
答案1
得分: 0
在API页面进行一些调试后(您可以实时尝试API),我发现API密钥的字段名称是apikey
。因此,以下代码应该可行:
import requests
api_key = "API-KEY-FROM-DEVELOPER-ACCOUNT"
api_url = "https://api.stm.info/pub/od/gtfs-rt/ic/v2/vehiclePositions"
# 准备带有API密钥的请求标头
headers = {
"apikey": api_key,
}
# 发送HTTP GET请求到API端点
response = requests.get(api_url, headers=headers);
print(f"{response.status_code}: {response.content}")
需要注意以下几点:
- 您的API密钥仅在您发布应用程序后才可用。选项位于应用程序编辑屏幕的底部。如果您的"应用程序"不显示为"已启用",则表示您尚未完成它,您的API密钥将不起作用。
- 响应是一个protobuf,而不是json。
使用Python语言绑定来读取结果会更容易。您可以使用以下示例(适用于python3):
from google.transit import gtfs_realtime_pb2
from urllib.request import Request, urlopen
api_key = "API-KEY-FROM-DEVELOPER-ACCOUNT"
api_url = "https://api.stm.info/pub/od/gtfs-rt/ic/v2/vehiclePositions"
feed = gtfs_realtime_pb2.FeedMessage()
request = Request(api_url)
request.add_header('apikey', api_key)
response = urlopen(request)
print(f'Status: {response.status_code}')
feed.ParseFromString(response.read())
for i, entity in enumerate(feed.entity):
if entity.HasField('vehicle') and entity.vehicle.HasField('position'):
pos = entity.vehicle.position
print(f'{i} lat: {pos.latitude}, long: {pos.longitude}')
注意:此翻译已经去掉了HTML编码的引号("
)以及HTML标签。
英文:
After some fiddling (in the APIs page you can try the APIs real time), I found out that the field name for the API key is apikey
. Thus, the following code should work:
import requests
api_key = "API-KEY-FROM-DEVELOPER-ACCOUNT"
api_url = f"https://api.stm.info/pub/od/gtfs-rt/ic/v2/vehiclePositions"
# Prepare the request headers with the API key
headers = {
"apikey": api_key,
}
# Send the HTTP GET request to the API endpoint
response = requests.get(api_url, headers=headers);
print(f"{response.status_code}: {response.content}")
A few points to notice:
- Your API key will only be available after you publish your application. The option will be on the bottom of the application editing screen. If your "Application" is not showing "Enabled", you didn't finish it and your API key will not work.
- The response is a protobuf, not a json.
It will be easier to use the Python language bindings to read the results. You can use the example below (adapted to python3):
from google.transit import gtfs_realtime_pb2
from urllib.request import Request, urlopen
api_key = "API-KEY-FROM-DEVELOPER-ACCOUNT"
api_url = f"https://api.stm.info/pub/od/gtfs-rt/ic/v2/vehiclePositions"
feed = gtfs_realtime_pb2.FeedMessage()
request = Request(api_url)
request.add_header('apikey', api_key)
response = urlopen(request)
print(f'Status: {response.status_code}')
feed.ParseFromString(response.read())
for i, entity in enumerate(feed.entity):
if entity.HasField('vehicle') and entity.vehicle.HasField('position'):
pos = entity.vehicle.position
print(f'{i} lat: {pos.latitude}, long: {pos.longitude}')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论