When do you use the Django Rest Framework

Quick Start

We're going to create a simple API that administrators can use to see and edit users and groups in the system.

Create a new Django Scheme: Tutorial, then create a new quickstart for the application

The composition of the program is as follows:

It may seem unusual for the application to build in the schedule file. Use the schema namespace to avoid conflict between application names and external modules.

Now for the first database synchronization:

We'll also create a first-time administrator. The password is password123. We will authenticate this user later in this example.

Once you've set up the database and first-time user and can proceed, open the application directory and we'll start programming ...

First, let's define some serializers. Create a new module tutorial / quickstart / serializers.py for data display

Notice that in this example we are using HyperlinkedModelSerializer. But you can also use the primary key and many other relationships

Hyperlink relationship is a good RESTful design

Views

tutorial / quickstart / views.py

Instead of writing a lot of view functions, we combine the same behaviors in objects (class) ..

If necessary, we can simply break them down into independent views. However, using view sets can make the view logic simple and clear.

Urls

tutorial / urls.py

Since we are using viewsets instead of the views function, we can automatically generate URL Conf for our API as long as we register viewsets with the router class.

If we want more control over API urls, we just need to use ordinary class-based views and explicitly write out the url conf.

Finally, we include standard login and logout views to make the API searchable. This is optional and useful when your API requires authentication and you want to use a searchable API.

Pagination (pagination)

tutorial / settings.py

Settings

 

Add 'Rest_framework' to INSTALLED_APPS

The above is complete.

Start server

Use our API on the command line through Curl

Or use tip

Or directly via the browser, via the URL ...

If you are using a browser, please ensure that the control module in the upper right corner is used to log in.