Django rest framework basic introduction and code examples

  • 2020-07-21 09:09:38
  • OfStack

This paper mainly studies the related contents of Django rest framework, and shares example as follows.

The Django REST framework is a powerful and flexible toolkit for building Web API.

1 reasons you might want to use the REST framework:

Web browsing API is a huge usability victory for your developers. The validation policy includes packages for OAuth1a and OAuth2. Supports serialization of ORM and non-ES21en data sources. If you don't need more powerful functionality, you can customize 1 slice - just use the feature-based general view. Extensive documentation and excellent community support. Used and trusted by Mozilla, Red Hat, Heroku and Eventbrite, etc.

Requirements

The REST framework requires the following:

Python (2.7, 3.2, 3.3, 3.4, 3.5) Django (1.8, 1.9, 1.10)

The following packages are optional:

coreapi (1.32.0+) - Supports schema generation. Markdown (2.1.0+) - Browse Markdown support for API. django-filter (1.0.1+) - Filtering support. django-crispy-forms-improved HTML display filter. django-guardian (1.1.1+) - Object-level permission support.

Installation

Install using pip, including any optional packages you...


pip install djangorestframework
pip install markdown    # Markdown support for the browsable API.
pip install django-filter # Filtering support

Add'rest_framework'to your INSTALLED_APPS setting.


INSTALLED_APPS = (
  ...
  'rest_framework',
)

If you plan to use the browsable API, you may also need to add the login and logout views of the REST framework. Add the following to your root ES74en.py file.


urlpatterns = [
  ...
  url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Note that the URL path can be anything you want, but you must include "rest_framework.urls" in the namespace of rest_framework. You can omit the namespace in Django 1.9+, and the REST framework will set it for you.

Example

Let's look at a simple example of API using the REST framework to build a simple model-supported API.

We will create a read/write API to access the information of our project users.

Any global Settings for the REST framework API are stored in a single configuration dictionary named REST_FRAMEWORK. First add the following to the ES103en.py module:


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 also add rest_framework to your INSTALLED_APPS.

We are ready to create our API. This is the root ES115en. py module of our project:


from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

 # Serializers define API Said. 
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

 # router provided 1 Automatic species determination URL conf Simple way. 
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

 Use automatic URL routing to connect to our API . 
#  In addition, we also include browsable API The login URL . 
urlpatterns = [
  url(r'^', include(router.urls)),
  url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))

You can now in http: / / 127.0.0.1:8000 / browser opens the API, and view the new API "users". If you use the login control in the upper right corner, you can also add, create, and delete users from the system.

conclusion

That is the basic introduction of Django rest framework. I hope it will be helpful to you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: