让我们看一个使用 REST 框架构建一个简单的模型支持的 API 的快速示例。

我们将创建一个读写 API,用于访问有关项目用户的信息。

REST 框架 API 的任何全局设置都保存在名为 REST_FRAMEWORK 的单个配置字典中。首先将以下内容添加到 settings.py 模块:

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'
    ]
}

我们现在准备创建我们的 API 了。这是我们项目的 root 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'))
]

你现在可以在浏览器中通过 http://127.0.0.1:8000/打开 API,并查看新的用户API。如果你使用右上角的登录控件,你还可以从系统添加,创建和删除用户。