django rest framework quick start tutorial

Django REST framework is a fast and flexible django plug-in, which is very convenient to build web API

Official website link

Key points of this chapter

  • How to prepare a project (create a test environment, install django/restframework, etc.)
  • Write seriallizer/view/url
  • Configure restframe work
  • test

Prepare the project

mkdir tutorial
cd tutorial

# Create a virtual environment through virtualenv, another Baidu about virtualenv
virtualenv env -p python3  # django 2.0 is not friendly to python2
source env/bin/activate  # Windows platform use ` env\Scripts\activate`

# Install Django and Django REST framework
pip install django
pip install djangorestframework

# Create a project
django-admin.py startproject tutorial
cd tutorial
django-admin.py startapp quickstart
cd ..

Synchronize the database through Python management.py migrate
After that, create an account through Python management.py createsuperuser. The recommended name is admin and password is password123

Write seriallizer/view/url

seriallizer (show data)

Create the file tutorial/quickstart/serializers.py. The code is as follows:

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

View (view file)

Open tutorial/quickstart/views.py and edit:

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

url (route)

Open tutorial/urls.py and edit:

from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# 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'))
]

Configure restframe work

Open tutorial/settings.py and add:

INSTALLED_APPS = (
    ...
    'rest_framework',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
    'PAGE_SIZE': 10
}

test

Run the project through Python management.py runserver

Test with httpie (linux)

Enter http -a admin:password123 http://127.0.0.1:8000/users/ under bash to test. The test is successful as follows:

HTTP/1.1 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 98
Content-Type: application/json
Date: Sat, 16 Dec 2017 13:20:49 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

[
    {
        "email": "yarving@qq.com", 
        "groups": [], 
        "url": "http://127.0.0.1:8000/users/1/", 
        "username": "admin"
    }
]

Test with browser

Open http://127.0.0.1:8000/users/ with a browser. You will be required to log in first. After logging in, you can see the following interface:

image.png

Tags: Django Python REST pip

Posted on Thu, 14 May 2020 08:57:09 -0700 by alsouno