注意:這是版本3的文檔。還提供了版本2的文檔。
Django REST framework 是一個強大且靈活的工具包,用以構建Web APIs。
為什么要使用REST framework?
- 在線可視的API,對于贏得你的開發者們十分有用
- 驗證策略涵蓋了OAuth1a和OAuth2
- 同時支持ORM和非ORM數據源的序列化
- 可以配置各個環節,若無需更多強大的特性,使用一般基于類(function-based)的視圖(views)即可
- 大量的文檔,強力的社區支持
-
大公司如同Mozilla和Eventbrite,也是忠實的使用者
image.png
Funding(資金來源)
REST framework is a collaboratively(合作地) funded project(基金項目). If you use REST framework commercially(商業化的) we strongly(強烈) encourage(建議) you to invest(投資) in its continued development(可持續發展) by signing up for a paid plan.(注冊付費計劃)
Every single(每次簡單) sign-up helps us make REST framework long-term financially(財政上) sustainable(財務上可持續發展)
Many thanks to all our wonderful sponsors(贊助商), and in particular to our premium backers(優質的支持者), Rover, Sentry, Stream, Machinalis, and Rollbar.
(非常感謝我們所有的優秀贊助商,特別是我們的優秀支持者, Rover, Sentry, Stream, Machinalis, and Rollbar.
)
配置要求( Requirements)
REST framework 有以下的要求:
Python (2.7, 3.2, 3.3, 3.4, 3.5,3.6)
Django (1.7+, 1.8, 1.9,,2.0)
下面是可選的包:
- coreapi (1.32.0+) - 模式生成支持。
- Markdown (2.1.0+) - Markdown為可視化 API 提供了支持.
- django-filter (1.0.1+) - 過濾支持.
- django-crispy-forms - 為過濾,提供了改良的HTML呈現.
- django-guardian (1.1.1+) - 對象層面的權限支持.
安裝 Installation
Install using pip
, including any optional packages you want...(使用pip安裝,包括任何你想要的可選包裹...)
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
...or clone the project from github.(或者從GitHub復制項目)
git clone git@github.com:encode/django-rest-framework.git
Add 'rest_framework'
to your INSTALLED_APPS
setting.
INSTALLED_APPS = (
...
'rest_framework',
)
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file.(如果您打算使用可瀏覽的API,您可能還需要添加REST框架的登錄和注銷視圖。將以下內容添加到您的根urls.py文件中。)
urlpatterns = [
...
url(r'^api-auth/', include('rest_framework.urls'))
]
Note that the URL path can be whatever you want.(注意,url路徑可以是任何你想要的。)
示例 Example
Let's take a look at a quick example of using REST framework to build a simple model-backed API.讓我們來看看一個使用REST framework構建一個簡單模型支持api的快速示例。
We'll create a read-write API for accessing information on the users of our project.(我們將創建一個讀寫api,用于訪問項目用戶的信息。)
Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK
. Start off by adding the following to your settings.py
module:(REST framework api的任何全局設置都保存在一個名為“rest_wramework”的配置詞典中。首先在“環境”模塊中添加以下內容:)
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
Don't forget to make sure you've also added rest_framework
to your INSTALLED_APPS
.(別忘了確保你已經在“INSTALLED_APPS”中添加了“rest_framework”。)
We're ready to create our API now. Here's our project's root urls.py
module:(我們準備好創建我們的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 define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.(現在,您可以在瀏覽器中輸入‘http://127.0.0.1:8000/’打開api,并查看您的新“用戶”api。如果您使用右上角的登錄控件,您也可以從系統中添加、創建和刪除用戶。)
快速啟動 Quickstart
Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.(等不及要開始了?快速啟動指南是最快的建立和運行的方式,并建立REST framework的apis。)
教程 Tutorial
The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.(本教程將幫助您完成組成REST框架的構建塊。這需要一點時間來完成,但是它會給你一個全面的理解如何把一切結合起來,并強烈推薦閱讀。)
5 - Relationships & hyperlinked APIs關系與超鏈接型API
6 - Viewsets & routers視圖組與路由
There is a live example API of the finished tutorial API for testing purposes, available here.這里有一個用于測試目的的完成教程API的實例化API,這里可獲得
API指南 API Guide
The API guide is your complete reference manual to all the functionality provided by REST framework.(API指南是您對REST框架提供的所有功能的完整參考手冊)
- Requests請求
- Responses響應
- Views視圖
- Generic views通用視圖
- Viewsets視圖集
- Routers路由器
- Parsers解析器
- Renderers渲染器
- Serializers序列化
- Serializer fields序列化字段
- Serializer relations序列化器的關系
- Validators驗證器
- Authentication認證
- Permissions權限
- Throttling節流
- Filtering過濾
- Pagination分頁
- Versioning版本控制
- Content negotiation內容協商
- Metadata元數據
- Schemas模式
- Format suffixes格式后綴
- Returning URLs返回的url
- Exceptions異常
- Status codes狀態碼
- Testing測試
- Settings設置
論題Topics
General guides to using REST framework.(使用REST框架的一般指南。)
- Documenting your API記錄你的api
- API ClientsAPI客戶端
- Internationalization國際化
- AJAX, CSRF & CORS
- HTML & Forms
- Browser enhancements瀏覽器增強
- The Browsable API可瀏覽的API
- REST, Hypermedia & HATEOASREST,超媒體和HATOOAS
- Third Party Packages第三方軟件包
- Tutorials and Resources教程和資源
- Contributing to REST framework有助于REST框架
- Project management項目管理
- 3.0 Announcement公告
- 3.1 Announcement
- 3.2 Announcement
- 3.3 Announcement
- 3.4 Announcement
- 3.5 Announcement
- 3.6 Announcement
- 3.7 Announcement
- 3.8 Announcement
- Kickstarter Announcement
- Mozilla Grant
- Funding
- Release Notes
- Jobs
發展 Development
See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework.(有關如何克隆存儲庫、運行測試套件以及向REST框架貢獻更改的信息,請參閱貢獻指南。)
支持Support
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.(要獲得支持,請參閱REST框架討論組,在IRC .freenode.net上嘗試#restframework通道,搜索IRC檔案,或者對Stack Overflow提出問題,確保包含“django-rest-framework”標簽。)
For priority support please sign up for a professional or premium sponsorship plan.(如需優先支持,請注冊專業或優質贊助計劃。)
For updates on REST framework development, you may also want to follow the author on Twitter.(對于REST框架開發的更新,您可能還希望在Twitter上跟隨作者。)
安全性 Security
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 rest-framework-security@googlegroups.com. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
許可證 License
Copyright (c) 2011-2017, 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.