快速入门

是时候编写你第一个 REST API。本指南假设你对 Flask 有一定的认识,并且已经安装了 Flask 和 Flask-RESTful。如果还没有安装的话,可以依照 安装 章节的步骤安装。

一个最小的 API

一个最小的 Flask-RESTful API 像这样:

1. from flask import Flask
2. from flask.ext import restful

4. app = Flask(__name__)
5. api = restful.Api(app)

7. class HelloWorld(restful.Resource):
8. def get(self):
9. return {'hello': 'world'}

11. api.add_resource(HelloWorld, '/')

13. if __name__ == '__main__':
14. app.run(debug=True)

把上述代码保存为 api.py 并且在你的 Python 解释器中运行它。需要注意地是我们已经启用了 Flask 调试 模式,这种模式提供了代码的重载以及更好的错误信息。调试模式绝不能在生产环境下使用。

1. $ python api.py
2. * Running on http://127.0.0.1:5000/

现在打开一个新的命令行窗口使用 curl 测试你的 API:

1. $ curl http://127.0.0.1:5000/
2. {"hello": "world"}

资源丰富的路由(Resourceful Routing)

Flask-RESTful 提供的最主要的基础就是资源(resources)。资源(Resources)是构建在 Flask 可拔插视图 之上,只要在你的资源(resource)上定义方法就能够容易地访问多个 HTTP 方法。一个待办事项应用程序的基本的 CRUD 资源看起来像这样:

1. from flask import Flask, request
2. from flask.ext.restful import Resource, Api

4. app = Flask(__name__)
5. api = Api(app)

7. todos = {}

9. class TodoSimple(Resource):
10. def get(self, todo_id):
11. return {todo_id: todos[todo_id]}

13. def put(self, todo_id):
14. todos[todo_id] = request.form['data']
15. return {todo_id: todos[todo_id]}

17. api.add_resource(TodoSimple, '/<string:todo_id>')

19. if __name__ == '__main__':
20. app.run(debug=True)

你可以尝试这样:

1. $ curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
2. {"todo1": "Remember the milk"}
3. $ curl http://localhost:5000/todo1
4. {"todo1": "Remember the milk"}
5. $ curl http://localhost:5000/todo2 -d "data=Change my brakepads" -X PUT
6. {"todo2": "Change my brakepads"}
7. $ curl http://localhost:5000/todo2
8. {"todo2": "Change my brakepads"}

或者如果你安装了 requests 库的话,可以从 python shell 中运行:

1. >>> from requests import put, get
2. >>> put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json()
3. {u'todo1': u'Remember the milk'}
4. >>> get('http://localhost:5000/todo1').json()
5. {u'todo1': u'Remember the milk'}
6. >>> put('http://localhost:5000/todo2', data={'data': 'Change my brakepads'}).json()
7. {u'todo2': u'Change my brakepads'}
8. >>> get('http://localhost:5000/todo2').json()
9. {u'todo2': u'Change my brakepads'}

Flask-RESTful 支持视图方法多种类型的返回值。同 Flask 一样,你可以返回任一迭代器,它将会被转换成一个包含原始 Flask 响应对象的响应。Flask-RESTful 也支持使用多个返回值来设置响应代码和响应头,如下所示:

1. class Todo1(Resource):
2. def get(self):
3. ## Default to 200 OK
4. return {'task': 'Hello world'}

6. class Todo2(Resource):
7. def get(self):
8. ## Set the response code to 201
9. return {'task': 'Hello world'}, 201

11. class Todo3(Resource):
12. def get(self):
13. ## Set the response code to 201 and return custom headers
14. return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}

端点(Endpoints)

很多时候在一个 API 中,你的资源可以通过多个 URLs 访问。你可以把多个 URLs 传给 Api 对象的 Api.add_resource() 方法。每一个 URL 都能访问到你的 Resource

1. api.add_resource(HelloWorld,
2. '/',
3. '/hello')

你也可以为你的资源方法指定 endpoint 参数。

1. api.add_resource(Todo,
2. '/todo/<int:todo_id>', endpoint='todo_ep')

参数解析

尽管 Flask 能够简单地访问请求数据(比如查询字符串或者 POST 表单编码的数据),验证表单数据仍然很痛苦。Flask-RESTful 内置了支持验证请求数据,它使用了一个类似 argparse 的库。

1. from flask.ext.restful import reqparse

3. parser = reqparse.RequestParser()
4. parser.add_argument('rate', type=int, help='Rate to charge for this resource')
5. args = parser.parse_args()

需要注意地是与 argparse 模块不同,reqparse.RequestParser.parse_args() 返回一个 Python 字典而不是一个自定义的数据结构。

使用 reqparse 模块同样可以自由地提供聪明的错误信息。如果参数没有通过验证,Flask-RESTful 将会以一个 400 错误请求以及高亮的错误信息回应。

1. $ curl -d 'rate=foo' http://127.0.0.1:5000/
2. {'status': 400, 'message': 'foo cannot be converted to int'}

inputs 模块提供了许多的常见的转换函数,比如 inputs.date() 和 inputs.url()。

使用 strict=True 调用 parse_args 能够确保当请求包含你的解析器中未定义的参数的时候会抛出一个异常。

args = parser.parse_args(strict=True)

数据格式化

默认情况下,在你的返回迭代中所有字段将会原样呈现。尽管当你刚刚处理 Python 数据结构的时候,觉得这是一个伟大的工作,但是当实际处理它们的时候,会觉得十分沮丧和枯燥。为了解决这个问题,Flask-RESTful 提供了 fields 模块和 marshal_with() 装饰器。类似 Django ORM 和 WTForm,你可以使用 fields 模块来在你的响应中格式化结构。

1. from collections import OrderedDict
2. from flask.ext.restful import fields, marshal_with

4. resource_fields = {
5. 'task':   fields.String,
6. 'uri':    fields.Url('todo_ep')
7. }

9. class TodoDao(object):
10. def __init__(self, todo_id, task):
11. self.todo_id = todo_id
12. self.task = task

14. ## This field will not be sent in the response
15. self.status = 'active'

17. class Todo(Resource):
18. @marshal_with(resource_fields)
19. def get(self, **kwargs):
20. return TodoDao(todo_id='my_todo', task='Remember the milk')

上面的例子接受一个 python 对象并准备将其序列化。marshal_with() 装饰器将会应用到由 resource_fields 描述的转换。从对象中提取的唯一字段是 task。fields.Url 域是一个特殊的域,它接受端点(endpoint)名称作为参数并且在响应中为该端点生成一个 URL。许多你需要的字段类型都已经包含在内。请参阅 fields 指南获取一个完整的列表。

完整的例子

在 api.py 中保存这个例子

1. from flask import Flask
2. from flask.ext.restful import reqparse, abort, Api, Resource

4. app = Flask(__name__)
5. api = Api(app)

7. TODOS = {
8. 'todo1': {'task': 'build an API'},
9. 'todo2': {'task': '?????'},
10. 'todo3': {'task': 'profit!'},
11. }

13. def abort_if_todo_doesnt_exist(todo_id):
14. if todo_id not in TODOS:
15. abort(404, message="Todo {} doesn't exist".format(todo_id))

17. parser = reqparse.RequestParser()
18. parser.add_argument('task', type=str)

20. ## Todo
21. ##   show a single todo item and lets you delete them
22. class Todo(Resource):
23. def get(self, todo_id):
24. abort_if_todo_doesnt_exist(todo_id)
25. return TODOS[todo_id]

27. def delete(self, todo_id):
28. abort_if_todo_doesnt_exist(todo_id)
29. del TODOS[todo_id]
30. return '', 204

32. def put(self, todo_id):
33. args = parser.parse_args()
34. task = {'task': args['task']}
35. TODOS[todo_id] = task
36. return task, 201

38. ## TodoList
39. ##   shows a list of all todos, and lets you POST to add new tasks
40. class TodoList(Resource):
41. def get(self):
42. return TODOS

44. def post(self):
45. args = parser.parse_args()
46. todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
47. todo_id = 'todo%i' % todo_id
48. TODOS[todo_id] = {'task': args['task']}
49. return TODOS[todo_id], 201

51. ##
52. ### Actually setup the Api resource routing here
53. ##
54. api.add_resource(TodoList, '/todos')
55. api.add_resource(Todo, '/todos/<todo_id>')

57. if __name__ == '__main__':
58. app.run(debug=True)

用法示例

1. $ python api.py
2. * Running on http://127.0.0.1:5000/
3. * Restarting with reloader

获取列表

1. $ curl http://localhost:5000/todos
2. {"todo1": {"task": "build an API"}, "todo3": {"task": "profit!"}, "todo2": {"task": "?????"}}

获取一个单独的任务

1. $ curl http://localhost:5000/todos/todo3
2. {"task": "profit!"}

删除一个任务

1. $ curl http://localhost:5000/todos/todo2 -X DELETE -v

3. > DELETE /todos/todo2 HTTP/1.1
4. > User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3
5. > Host: localhost:5000
6. > Accept: */*
7. >
8. * HTTP 1.0, assume close after body
9. < HTTP/1.0 204 NO CONTENT
10. < Content-Type: application/json
11. < Content-Length: 0
12. < Server: Werkzeug/0.8.3 Python/2.7.2
13. < Date: Mon, 01 Oct 2012 22:10:32 GMT

增加一个新的任务

1. $ curl http://localhost:5000/todos -d "task=something new" -X POST -v

3. > POST /todos HTTP/1.1
4. > User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3
5. > Host: localhost:5000
6. > Accept: */*
7. > Content-Length: 18
8. > Content-Type: application/x-www-form-urlencoded
9. >
10. * HTTP 1.0, assume close after body
11. < HTTP/1.0 201 CREATED
12. < Content-Type: application/json
13. < Content-Length: 25
14. < Server: Werkzeug/0.8.3 Python/2.7.2
15. < Date: Mon, 01 Oct 2012 22:12:58 GMT
16. <
17. * Closing connection #0
18. {"task": "something new"}

更新一个任务

1. $ curl http://localhost:5000/todos/todo3 -d "task=something different" -X PUT -v

3. > PUT /todos/todo3 HTTP/1.1
4. > Host: localhost:5000
5. > Accept: */*
6. > Content-Length: 20
7. > Content-Type: application/x-www-form-urlencoded
8. >
9. * HTTP 1.0, assume close after body
10. < HTTP/1.0 201 CREATED
11. < Content-Type: application/json
12. < Content-Length: 27
13. < Server: Werkzeug/0.8.3 Python/2.7.3
14. < Date: Mon, 01 Oct 2012 22:13:00 GMT
15. <
16. * Closing connection #0
17. {"task": "something different"}