如何在Python中使用路径参数发送GET请求

2024-09-22 16:43:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用Python处理EatStreet公共API的GET请求时遇到问题。我已经成功地使用了站点上的其他端点,但是我不确定如何处理这个实例中的路径参数。你知道吗

此curl请求返回200:

卷曲-X得到\ -H'X-Access-Token:API\u EXPLORER\u AUTH\u 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/


Tags: httpscomtokenapi参数getaccessresponse
1条回答
网友
1楼 · 发布于 2024-09-22 16:43:29

Passing Parameters In URLs

You often want to send some sort of data in the URL’s query string. If you were constructing the URL by hand, this data would be given as key/value pairs in the URL after a question mark, e.g. httpbin.org/get?key=val. Requests allows you to provide these arguments as a dictionary of strings, using the params keyword argument. As an example, if you wanted to pass key1=value1 and key2=value2 to httpbin.org/get, you would use the following code:

    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

Note that any dictionary key whose value is None will not be added to the URL’s query string.

You can also pass a list of items as a value:

    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)

相关问题 更多 >