首页 > 解决方案 > 如何在 Python 中发送带有路径参数的 GET 请求

问题描述

我在处理来自 EatStreet Public API 的使用 Python 的 GET 请求时遇到问题。我已经在站点上的其他端点上取得了成功,但我不确定在这种情况下如何处理路径参数。

此 curl 请求返回 200:

curl -X GET \ -H 'X-Access-Token: API_EXPLORER_AUTH_KEY ' \ ' https://eatstreet.com/publicapi/v1/restaurant/90fd4587554469b1f15b4f2e73e761809f4b4bcca52eedca/menu?includeCustomizations=false '

这是我目前所拥有的,但我不断收到错误代码 404。我尝试了多种其他方法来处理参数和标题,但似乎没有任何效果。

api_url = 'https://eatstreet.com/publicapi/v1/restaurant/
90fd4587554469b1f15b4f2e73e761809f4b4bcca52eedca/menu'
headers = {'X-Access-Token': apiKey}

def get_restaurant_details():

        response = requests.request("GET", api_url, headers=headers)
        print(response.status_code)

        if response.status_code == 200:
                return json.loads(response.content.decode('utf-8'))
        else:
                return None

这是 EatStreet 公共 API 的链接: https ://developers.eatstreet.com/

标签: pythonresthttpget

解决方案


在 URL 中传递参数

您经常希望在 URL 的查询字符串中发送某种数据。如果您手动构建 URL,这些数据将在 URL 中以问号后的键/值对形式给出,例如 httpbin.org/get?key=val。Requests 允许您使用 params 关键字参数将这些参数作为字符串字典提供。例如,如果您想将 key1=value1 和 key2=value2 传递给 httpbin.org/get,您可以使用以下代码:

    payload = {'key1': 'value1', 'key2': 'value2'}
    r = requests.get('https://httpbin.org/get', params=payload)

您可以通过打印 URL 看到 URL 已正确编码:

    print(r.url)
    https://httpbin.org/get?key2=value2&key1=value1

请注意,任何值为 None 的字典键都不会添加到 URL 的查询字符串中。

您还可以将项目列表作为值传递:

    payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
    r = requests.get('https://httpbin.org/get', params=payload)
    print(r.url)
    https://httpbin.org/get?key1=value1&key2=value2&key2=value3

所以在你的情况下,它可能看起来像

parameters = {'includeCustomizations':'false'}
response = requests.request("GET", api_url, params=parameters, headers=headers)

推荐阅读