本文通过学习 https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask 而来,例子和数据库例子也是来自该文。
本文先介绍api的使用,然后通过几个例子一步步解说rest api 的设计。例子包括:第一个基本例子,有返回的例子,带参数查询的例子,数据库查询的例子。理解这几个例子,你就入门了。
理解api
下面是使用api的例子:
http://chroniclingamerica.loc.gov/search/pages/results/?format=json&proxtext=fire
这个返回一个json 数据集。
这里包括以下三个部分。
基本的url 部分是
http://chroniclingamerica.loc.gov
路径是:
/search/pages/results/
参数部分是:
?format=json&proxtext=fire
准备
安装好python 3 和 flask
pip install flask
建立一个目录projects,然后在这个目录下建立一个api的目录。
第一个例子
在这个目录下建立一个api.py 的python文件,内容如下:
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"
app.run()
在命令行下执行python api.py
可以看到类似下面的提示内容:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
按照这个提示在浏览器里输入 http://127.0.0.1:5000/ 就可以看到网页:
这是显示的第一个界面。
有数据返回的例子
下面添加一点内容,增加返回一个数据表这个api。更改这个文件的代码如下:
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
# Create some test data for our catalog in the form of a list of dictionaries.
books = [
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'},
{'id': 1,
'title': 'The Ones Who Walk Away From Omelas',
'author': 'Ursula K. Le Guin',
'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
'published': '1973'},
{'id': 2,
'title': 'Dhalgren',
'author': 'Samuel R. Delany',
'first_sentence': 'to wound the autumnal city.',
'published': '1975'}
]
@app.rou