【问题标题】:Requests library to send json for API Post请求库为 API Post 发送 json
【发布时间】:2018-10-02 15:52:02
【问题描述】:

我正在尝试从以下位置连接到 API:https://devzone.revulytics.com/docs/API/authentication.html#authentication-top

我发现了Requests库并安装了它,然后找到this post和其他一些,最后编译了这段代码:

import requests

apiURL = "http://api.revulytics.com"
header = {'Host': 'api.revulytics.com', 
          'Content-Type': 'application/json',
          'Accept': 'application/json'}
json = {"user": "testuser@test.com",
        "password": "mypassword1"}

r = requests.post(apiURL, headers=header, json=json)
print(r.status_code)

我把代码弄乱了很多,但它似乎仍然无法正常工作 - 我确实用自己的方式更改了用户和密码。

我在运行 status_code 时不断收到 404,这意味着我无法连接到 API。对此有什么想法吗?

【问题讨论】:

    标签: python json python-3.x api post


    【解决方案1】:

    404 表示没有名为/ 的端点。根据您链接到的页面,端点是/auth/login

    所以你想要

    apiURL = "https://api.revulytics.com/auth/login"
    

    这将使 404 消失。

    这是我的脚本和响应

    $ cat p.py
    import requests
    
    apiURL = "https://api.revulytics.com/auth/login"
    header = {'Host': 'api.revulytics.com', 
              'Content-Type': 'application/json',
              'Accept': 'application/json'}
    json = {"user": "testuser@test.com",
            "password": "mypassword1"}
    
    r = requests.post(apiURL, headers=header, json=json)
    print(r.status_code, r.json())
    
    $ python3 p.py
    403 {'status': 'AUTH ERROR', 'reason': 'Wrong credentials'}
    

    【讨论】:

    • 谢谢你,修复了 404 错误!现在收到 400 错误,但我更接近{"errors": ["There was a JSON problem. Correct JSON is required"]}
    • 你怎么知道auth/login需要被指向?
    • 我点击了你提供的链接,上面写着“POST /auth/login”。 POST 之后的部分进入 url。它实际上只是记录 API 的一种标准方式。
    猜你喜欢
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2017-10-12
    • 1970-01-01
    • 2012-12-04
    • 2014-06-25
    • 2017-04-02
    相关资源
    最近更新 更多