注意:这是版本v.3+的REST framework文档。
Django REST framework 是一个强大且灵活的工具包,用以构建Web APIs。
为什么要使用REST framework?
- 在线可视的API,对于赢得你的开发者们十分有用
- 验证策略涵盖了OAuth1a和OAuth2
- 同时支持ORM和非ORM数据源的序列化
- 可以配置各个环节,若无需更多强大的特性,使用一般基于类(function-based)的视图(views)即可
- 大量的文档,强力的社区支持
- 大公司如同Mozilla和Eventbrite,也是忠实的使用者
上图:可视API的截图
REST framework 有以下的要求:
下面是可选的包:
使用pip
安装框架及所有的你需要的可选依赖包
pip install djangorestframework
pip install markdown
pip install django-filter
…又或者从github上clone该项目
git clone git@github.com:tomchristie/django-rest-framework.git
(译者注:假设你已经创建好了项目)
将 'rest_framework'
添加到你的 'INSTALLED_APPS'
设置里
INSTALLED_APPS = (
...
'rest_framework',
)
(译者注:如果你没有创建项目,可以跟着后续教程,一步步创建项目)
如果你需要使用可视化的API,你也许就需要添加REST Framework的登陆/登出视图。在你的根 urls.py
文件里,添加下面的内容:
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
需要留意的是,URL路径可以任意编写,但你必须include 'rest_framework.urls'
,且使用'rest_framework'
这个namespace(命名空间)。如果你的Django是1.9+版本,你也可以不写namespace,REST framework会帮你自动设置。
让我们看一个简单用例:如何用REST framework 来搭建一个简单的支持modle的API。
我们将创建一个读/写API,来处理我们项目中的用户信息。
任何REST framework的全局设置,都存放在一个配置字典(dictionary,有些语言如java中的map)中,,名为REST_FRAMEWORK
。我们从以下的操作开始,把下面的内容添加到你的settings.py
模块中:
REST_FRAMEWORK = {
# 使用Django的标准`django.contrib.auth`权限管理类,
# 或者为尚未认证的用户,赋予只读权限.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
别忘了,确保你已经将 rest_framework
添加到你的INSTALLED_APPS
中。
现在我们已做好准备,来创建我们的API了。这是我们的项目根下urls.py
模块:
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# Serializers定义了API的表现.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets 定义了 视图(view) 的行为.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers 提供了一种简单途径,自动地配置了URL。
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# 使用自动的URL路由,让我们的API跑起来。
# 此外,我们也包括了登入可视化API的URLs。
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
现在你可以在浏览器的http://127.0.0.1:8000/里,打开你新建的’users’ API了。使用右上角的登陆控制,可以对系统用户进行新增和删除操作。
迫不及待了?快速开始教程 (quickstart ),是使用REST framework来构建API的最快途径。
本教程会带你过一遍REST框架的使用环节。这会花你一点时间,但也会给你一个全局的理解,所有东西是如何组合在一起的,我们强烈建议您阅读本教程。
教程 | 英文教程 | 中文教程 | 翻译状态 |
---|---|---|---|
1 | Serialization | 序列化 | 翻译完毕 |
2 | Requests & Responses | 请求与相应 | 翻译完毕 |
3 | Class based views | 基于类的视图 | 翻译完毕 |
4 | Authentication & permissions | 认证与权限 | 翻译中 |
5 | Relationships & hyperlinked APIs | 关系与超链接型API | 待翻译 |
6 | Viewsets & routers | 视图组与路由 | 待翻译 |
作为测试使用,我们教程中完成的API 在这里展示。
API指南:是你完整的参考手册,涵盖REST framework提供的所有功能.
导引 | 英文教程 | 中文教程 | 翻译状态 |
---|---|---|---|
1 | Requests | 待翻译 | |
2 | Responses | 待翻译 | |
3 | Views | 待翻译 | |
4 | Generic views | 待翻译 | |
5 | Viewsets | 待翻译 | |
6 | Routers | 待翻译 | |
7 | Parsers | 待翻译 | |
8 | Renderers | 待翻译 | |
9 | Serializers | 待翻译 | |
10 | Serializer fields | 待翻译 | |
11 | Serializer relations | 待翻译 | |
12 | Validators | 待翻译 | |
13 | Authentication | 待翻译 | |
14 | Permissions | 待翻译 | |
15 | Throttling | 待翻译 | |
16 | Filtering | 待翻译 | |
17 | Pagination | 待翻译 | |
18 | Versioning | 待翻译 | |
19 | Content negotiation | 待翻译 | |
20 | Metadata | 待翻译 | |
21 | Format suffixes | 待翻译 | |
22 | Returning URLs | 待翻译 | |
23 | Exceptions | 待翻译 | |
24 | Status codes | 待翻译 | |
25 | Testing | 待翻译 | |
26 | Settings | 待翻译 |
Topics
General guides to using REST framework.
See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework.
For support please see the REST framework discussion group, try the #restframework channel on irc.freenode.net, search the IRC archives, or raise a question on Stack Overflow, making sure to include the ‘django-rest-framework’ tag.
Paid support is available from DabApps, and can include work on REST framework core, or support with building your REST framework API. Please contact DabApps if you’d like to discuss commercial support options.
For updates on REST framework development, you may also want to follow the author on Twitter.
Follow @_tomchristie
If you believe you’ve found something in Django REST framework which has security implications, please do not raise the issue in a public forum.
Send a description of the issue via email to [email protected]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
Copyright (c) 2011-2016, Tom Christie All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.