首页 > 解决方案 > 404 错误 API 调用 Pexels Python

问题描述

我想用 Python 下载带有 Pexels API(文档)的图像。首先,我通过执行以下操作获取图片的 ID:

import requests
image_base_url = 'https://api.pexels.com/v1/search'
api_key = 'my_api_key'
my_obj = {'query':'Stock market'}
x = requests.get(image_base_url,headers = {'Authorization':api_key},data = my_obj)
print(x.text)

然后,我为我想要的图像获取一个 ID 并运行它:

photo_request_link = 'https://api.pexels.com/v1/photos/'
photo_id = {'id':159888}
final_photo = requests.get(photo_request_link,headers = {'Authorization':api_key},data=photo_id)
print(final_photo)

但结果是 404 错误。知道为什么吗?

标签: pythonpython-3.xapipython-requests

解决方案


id 是 URL 路径的一部分,而不是查询字符串。请参阅文档中的示例 ( https://api.pexels.com/v1/photos/2014422 )。您应该将其附加到 URL,例如:

photo_request_link = f'https://api.pexels.com/v1/photos/{id}'

推荐阅读