Django REST framework quick start

Keywords: Python Django REST pip

start

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

Project settings

Create a new django project named: < tutorial >, and then create a new app named: < QuickStart >.

# Create the project directory

mkdir tutorial

cd tutorial

 

# Create a virtual environment to isolate our package dependencies locally

python3 -m venv env

source env/bin/activate  # On Windows use `env\Scripts\activate`

 

# Install Django and Django REST framework into the virtual environment

pip install django

pip install djangorestframework

 

# Set up a new project with a single application

django-admin startproject tutorial .  # Note the trailing '.' character

cd tutorial

django-admin startapp quickstart

cd ..

 

The layout of the project should be as follows:

$ pwd
<some path>/tutorial
$ find .
.
./manage.py
./tutorial
./tutorial/__init__.py
./tutorial/quickstart
./tutorial/quickstart/__init__.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py

 

This project directory looks different. Its application is built in the project directory. Using the project's namespace avoids naming conflicts with external modules (this topic is beyond the scope of this article).

Now, we can start to synchronize our database.

python manage.py migrate

 

Same. We also need to create an initial user and name it: < admin >. Set the password to: < password123 >.

python manage.py createsuperuser --email admin@example.com --username admin

 

When you have set up the database and created the initial user, open the application < QuickStart > directory and start writing code~

Serialization tool( Serializers)

The first step is to define some serializers. Let's create a new module. Name it: < tutorial / QuickStart / serializers. Py >. We will use this module to describe our data.

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 the serialization tools < userserializer > and < groupserializer > we are using now inherit from the parent class < hyperlinkedmodelserializer >. This parent class allows us to describe the relationship between data tables in a hyperlink way. You can also use the primary key < primary key > or other ways to associate the relationships between data tables, but using hyperlinks is a very restful design.

Views

The second step. We need to get to the view part. Open < tutorial / QuickStart / views. Py > 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):
    """
    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

 

We use the class < viewsets > to integrate the parts of view functions that have consistent functions. So you don't need to write many view functions.

Of course, we can easily separate the integrated views when we need to customize them, but using < viewsets > can make our logic clearer and our code more concise.

Routing settings( URLs)

Next, it's time to set up our API routing. Open < tutorial / URLs. Py >.

from django.urls import include, path
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 = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

 

Because we use the < viewsets > instance instead of the original view, we can automatically generate the corresponding route for us by registering our < viewsets > instance in the < defaultrouter > instance.

Of course, if we want to customize the route to make it more functional, we can discard this function and use the normal class based view to define the route.

Finally, the user login and logout views are placed in the browsable API page. This is an option if you need to use browsable API pages and user management.

paging

Paging allows you to control how many objects are displayed per page. To use it, add the following code to the file < tutorial / settings. Py >

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

 

Set up

Open the setting module < tutorial / settings. Py > and add the < rest > framework > to < installed > apps >. As follows:

INSTALLED_APPS = [
    ...
    'rest_framework',
]

 

We have finished the above. A simple user management API, and can be quickly accessed on the browser, testing the API. After reading the above, you may think: "wtf?????????????!"???!!!. What is this? ". Next we will do some tests to help you understand. What did we do.

Test API

Now we can start testing the API we just built. But before that, we set a small goal, such as let the program run first.

python manage.py runserver

 

If the small goal is not achieved. Please look at the error message and then go back and look at the code.

Next we can access our API. You can access it from the command line using the curl tool:

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 the Httpie tool:

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 use the browser directly. Open link: http://127.0.0.1:8000/users/

 

If you are accessing through a browser, you need to log in at the top right corner. Because this management tool is for admin. Visitors cannot access it.

If you want to further learn and understand how REST framework encapsulates these functions step by step. Please continue to watch the guidance article or read our API directly.

The above is the whole content of this article. If you can't understand it, you need to use django to do several small projects to get familiar with the business process of django web application.

Posted by skymanj on Sat, 15 Feb 2020 00:42:00 -0800