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

标签 python rest http get

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

此curl请求返回200:

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

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

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 公共(public) API 的链接: https://developers.eatstreet.com/

最佳答案

<强> 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)

关于python - 如何在Python中发送带有路径参数的GET请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57437704/

相关文章:

python - 如何为多个数据框列制作管道?

java - 在 Play 中返回 HTTP 状态 "created"!框架

android - 什么时候需要明确指定 application/json Content-Type

java - 如何在不使用tomcat的情况下运行jersey-server webservice服务器

php - laravel file_get_contents ('php://input')不工作

python - 如何在 django 中检查 BASE_DIR?

Python 文件附加错误

python - Flask-SocketIo,如何在python线程和socketio.start_background_task线程之间共享数据?

android - 客户端接收状态 307 的正确行为

node.js - NodeJS HTTP 服务器和 Console.log