测试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错误,表示需要重新获取令牌