创建博客-使用HTTPie测试Web服务

测试Web服务时必须使用HTTP客户端,最常使用的两个在命令行中测试Web服务的客户端是curl和HTTPie,后者的命令行更简洁,可读性也更高,HTTPie也是用pip安装

GET请求可按照下面方式发起(以匿名用户):


(env) PS D:\flasky> http --json --auth : GET http://127.0.0.1:5000/api/v1.0/posts/
HTTP/1.0 200 OK
Content-Length: 4217
Content-Type: application/json
Date: Tue, 13 Sep 2016 11:43:18 GMT
Server: Werkzeug/0.11.10 Python/2.7.12


{
    "count": 104,
    "next": "http://127.0.0.1:5000/api/v1.0/posts/?page=2",
    "posts": [
        {
            "author": "http://127.0.0.1:5000/api/v1.0/users/2",
            "body": "I'm happy",
            "comment_count": 0,
            "comments": "http://127.0.0.1:5000/api/v1.0/posts/1/comments/",
            "doby_html": null,
            "timestamp": "Wed, 31 Aug 2016 03:13:50 GMT",
            "url": "http://127.0.0.1:5000/api/v1.0/posts/1"
        },

# ....

下面这个命令发送POST以添加一篇新博客文章:

(venv) $ http --auth<email>:<password> --json POST \
> http://127.0.0.1:5000/api/v1.0/posts/ \
> "body=I'm adding a post from the command line."

HTTP/1.0 201 CREATED
Content-Length: 354
Content-Type: application/json
Date: Tue, 13 Sep 2016 13:01:28 GMT
Location: http://127.0.0.1:5000/api/v1.0/posts/108
Server: Werkzeug/0.11.10 Python/2.7.12

{
    "author": "http://127.0.0.1:5000/api/v1.0/users/2",
    "body": "I'm adding a post from the PS.",
    "comment_count": 0,
    "comments": "http://127.0.0.1:5000/api/v1.0/posts/108/comments/",
    "doby_html": "<p>I'm adding a post from the PS.</p>",
    "timestamp": "Tue, 13 Sep 2016 13:01:28 GMT",
    "url": "http://127.0.0.1:5000/api/v1.0/posts/108"
}

想要使用认证令牌,可向/api/v1.0/token发送请求:

(env)$ http --auth <你账户>:<你密码> --json GET \
> http://127.0.0.1:5000/api/v1.0/token

HTTP/1.0 200 OK
Content-Length: 163
Content-Type: application/json
Date: Tue, 13 Sep 2016 13:03:26 GMT
Server: Werkzeug/0.11.10 Python/2.7.12

{
    "expiration": 3600,
    "token": "eyJhbGciOiJIUzI1NiIsImV4cCI6MTQ3Mzc3NTQwNiwiaWF0IjoxNDczNzcxODA2fQ.eyJpZCI6Mn0.5UQ2dmNqtQ9v8p
QRjmND4N9xdXlhcuqN2_wnRtFWyag"
}

接下来的一小时中,这个令牌可用于访问API,请求时要和空密码一起发送:

(env) http --json --auth <你的令牌> GET http://127.0.0.1:5000/api/v1.0/posts/

令牌过期后,请求会返回401错误,表示需要重新获取令牌

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值