Django REST Framework (DRF) tutorial: getting started

We will create a simple API that allows administrator users to view and edit users and groups in the system.

Project settings

Create a new django project called tutorial and start a new app called quickstart.

# Create the project directory mkdir tutorial
cd tutorial# Create a virtualenv to isolate our local package dependencies
source env/bin/activate  # stay Windows Use under `env\Scripts\activate`# Install Django and Django REST frameworkpip install django in the created virtual environment
pip install djangorestframework# Create a new project and a single application django-admin.py startproject tutorial .  # Note the '.' sign cd tutorial at the end
django-admin.py startapp quickstart
cd ..

Now sync your database for the first time:

python manage.py migrate

We will also create an initial user named admin with a password of password123. We will validate the user later in this example.

python manage.py createsuperuser

When you have established a database and initial users, and are ready to start. Open the directory of the application and we're about to start coding

Serializers

First, we need to define some serializers. We created a file called tutorial/quickstart/serializers.py to use as our data representation.

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

Note that in this example, we use the hyperlink relationship, using the hyperlink modelserializer. You can also use primary keys and various other relationships, but hyperlinks are a good RESTful design.

Views

OK, let's write some more views. Open the tutorial/quickstart/views.py file and start writing code.

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


class UserViewSet(viewsets.ModelViewSet):
    """
    Allow users to view or edit API route.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    Allow groups to view or edit API route.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

Instead of writing multiple views, we group all common behaviors into a class called ViewSets.

We can easily decompose these details into a single view if we need it, but using viewsets can make the view logic well organized and very concise.

URLs

OK, now let's start writing URLs of the connection API in tutorial/urls.py.

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)

# Connect to our API using automatic URL routing.
# In addition, we also include the login URL that supports the browser browsing API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Because we use viewsets instead of views, we can automatically generate the URL conf of the API by simply registering the view with the router class.

Thirdly, if we need more control over the API URL, we can simply pull it out, use the regular class based view, and explicitly write the URL conf.

Finally, we will include the default login and logout views for APIs that support browser browsing. This is optional, but they are useful if your API requires authentication and you want to use an API that supports browser browsing.

Settings

We also want to set some global settings. We want to open paging. We want our API to be used only by administrators. The setting modules are in tutorial/settings.py.

INSTALLED_APPS = (
    ...
    'rest_framework',
)

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

All right, we're done.

Test our API

We can now test the API we built. We start the server from the command line.

python manage.py runserver

We can now access our API from the command line, using things like curl

bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

Or use httpie, command line tools

bash: http -a admin:password123 http://127.0.0.1:8000/users/

HTTP/1.1 200 OK
...
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://localhost:8000/users/1/",
            "username": "paul"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

Or go directly to the URL through the browser http://127.0.0.1:8000/users/ …

If you are using a browser, be sure to log in using the upper right corner.

excellent! That's it!

Reference link: https://www.django.cn/course/show-20.html

Tags: Python Linux Django

Posted on Wed, 24 Nov 2021 11:09:25 -0500 by igoy