如何在Python中发送带有路径参数的GET请求

时间:2019-08-09 22:16:06

标签: python rest http get

我在使用Python从EatStreet Public API获得GET请求时遇到了麻烦。我在站点上的其他端点上都取得了成功,但是我不确定在这种情况下如何处理路径参数。

此curl请求返回200:

curl -X GET \  -H'X访问令牌: 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/

1 个答案:

答案 0 :(得分:0)

Passing Parameters In URLs

  

您通常希望在URL的查询字符串中发送某种数据。如果您是手动构建网址,则此数据会在网址中以问号(例如, httpbin.org/get?key=val。请求允许您使用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
  

请注意,任何值为“无”的字典键都不会添加到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)