flask-restful:使用python构建restful api
随着现代互联网服务的崛起,restful api已成为通信协议的标准。为了开发高质量的restful api, python有一个高效的框架, flask-restful。本文将介绍什么是flask-restful以及如何使用python构建restful api。
第一部分:了解restful api
rest(表述性状态转移)是基于http协议的一种web服务的架构风格,它允许客户端请求访问和获取资源,并允许服务端返回请求的资源。api(应用程序编程接口)则是程序和系统之间的通信协议,它允许不同的应用程序通过定义的接口相互通信,从而实现完成特定的任务。restful api由两部分组成:资源(uri)和行为(http方法)。
资源是restful api的核心,即对内部数据的表述。 uri(统一资源标识符)指定了每个资源的位置,每个资源都有一个唯一的uri。另一方面,行为指定了如何访问和操作资源。 restful api使用http方法来定义这些操作,例如,get方法用于检索资源,post方法用于创建资源,put方法用于更新资源,delete方法用于删除资源。
第二部分:介绍flask-restful
flask-restful是flask的扩展模块,是一种python的restful框架。它为构建restful api提供了简化的方法和工具。 flask-restful的优点如下:
1、易于使用
flask-restful是一个轻量级的框架,基于flask框架。它提供了一组简单的工具,可以帮助开发人员快速构建 restful api,而不需要编写大量的重复代码。
2、快速开发
由于一些简化的方法,如请求参数解析和路由创建,可以显着减少api的开发时间。
3、对扩展和定制提供了支持
flask-restful提供了灵活的扩展和自定义点,开发人员可以根据需要扩展其功能。
4、文档非常详细
flask-restful的文档非常详细,易于学习和使用。
第三部分:如何使用flask-restful
接下来,我们将介绍如何使用flask-restful来构建restful api。我们将创建一个简单的api,用于管理电影数据。这个api将允许客户端进行以下操作:
1、列出所有电影
2、获取一个电影的详细信息
3、添加新电影
4、更新电影信息
5、删除电影记录
首先,安装及配置flask-restful并创建python虚拟环境。使用以下命令安装flask-restful(确保已安装pip):
pip install flask-restful
接下来,创建一个app.py文件。该文件必须导入所需的模块和库。这个文件将定义并实现flask应用程序。
from flask import flask, requestfrom flask_restful import resource, api, reqparseapp = flask(__name__)api = api(app)
此处我们引入了flask和flask-restful的库及模块。接下来,让我们定义一些虚拟数据。
movies = [{ 'id': 1, 'title': 'the shawshank redemption', 'director': 'frank darabont', 'year_released': 1994},{ 'id': 2, 'title': 'forrest gump', 'director': 'robert zemeckis', 'year_released': 1994},{ 'id': 3, 'title': 'the matrix', 'director': 'the wachowski brothers', 'year_released': 1999},{ 'id': 4, 'title': 'léon: the professional', 'director': 'luc besson', 'year_released': 1994},{ 'id': 5, 'title': 'the dark knight', 'director': 'christopher nolan', 'year_released': 2008},{ 'id': 6, 'title': 'interstellar', 'director': 'christopher nolan', 'year_released': 2014},{ 'id': 7, 'title': 'inception', 'director': 'christopher nolan', 'year_released': 2010},{ 'id': 8, 'title': 'the lord of the rings: the fellowship of the ring', 'director': 'peter jackson', 'year_released': 2001},{ 'id': 9, 'title': 'gladiator', 'director': 'ridley scott', 'year_released': 2000},{ 'id': 10, 'title': 'the godfather', 'director': 'francis ford coppola', 'year_released': 1972}]
现在,创建5个不同的资源来处理5个不同的http请求:get,post,put,delete。
class movielist(resource): def get(self): return { 'movies': movies } def post(self): parser = reqparse.requestparser() parser.add_argument('title', type=str, required=true, help='title is required.') parser.add_argument('director', type=str, required=true, help='director is required.') parser.add_argument('year_released', type=int, required=true, help='year must be a number.') args = parser.parse_args() movie = { 'id': len(movies) + 1, 'title': args['title'], 'director': args['director'], 'year_released': args['year_released'] } movies.append(movie) return movie, 201class movie(resource): def get(self, movie_id): movie = next(filter(lambda x:x['id']==movie_id, movies), none) return {'movie': movie}, 200 if movie else 404 def put(self, movie_id): parser = reqparse.requestparser() parser.add_argument('title', type=str, required=true, help='title is required.') parser.add_argument('director', type=str, required=true, help='director is required.') parser.add_argument('year_released', type=int, required=true, help='year must be a number.') args = parser.parse_args() movie = next(filter(lambda x:x['id']==movie_id, movies), none) if movie is none: movie = {'id': movie_id, 'title': args['title'], 'director': args['director'], 'year_released': args['year_released']} movies.append(movie) else: movie.update(args) return movie def delete(self, movie_id): global movies movies = list(filter(lambda x:x['id']!=movie_id, movies)) return {'message': 'movie deleted.'}, 200
这些资源被映射到与url相关的路径中。
api.add_resource(movielist, '/movies')api.add_resource(movie, '/movies/<int:movie_id>')
现在,启动flask应用程序并检查本地主机( http://127.0.0.1:5000/movies ),我们可以看到刚刚创建的api列表:
{"movies": [ { "director": "frank darabont", "id": 1, "title": "the shawshank redemption", "year_released": 1994 }, ... ]}
现在,我们可以使用post方法添加一个新电影。
import requestsurl = 'http://localhost:5000/movies'data = {"title": "the green mile", "director": "frank darabont", "year_released": "1999"}res = requests.post(url, data=data)
完整的请求和响应如下所示:
<response [201]>{'id': 11, 'title': 'the green mile', 'director': 'frank darabont', 'year_released': 1999}
我们还可以使用put方法来更新电影信息。
url = 'http://localhost:5000/movies/11'data = {"title": "the green mile", "director": "frank darabont", "year_released": "1999"}res = requests.put(url, data=data)
最后,让我们删除一个电影。
url = 'http://localhost:5000/movies/11'res = requests.delete(url)
我们创建了一个简单的restful api,使用flask-restful框架使其易于开发和维护。restful api是开发网络应用程序的必不可少的组件,它允许客户端对资源进行访问和更新,并强调uri和http方法。同时使用flask-restful可以加快团队的开发速度并简化代码。
以上就是flask-restful:使用python构建restful api的详细内容。
