This is the seventh day of my participation in the More text Challenge. For details, see more text Challenge

When using Django for separate development, it is common to create RESTful apis with the Django-REST-Framework framework. For details about the framework and version requirements, see the official address: www.django-rest-framework.org

This article uses django-REST-Framework as an example to learn how to use django-REST-Framework.

It consists of the following five steps:

  1. Creating a Django project
  2. Create the ORM model
  3. Load the Django REST Framework
  4. Serialization model
  5. Create the view and URL to load the data

1. Create a Django project

Create django_rest

django-admin startproject django_rest
Copy the code

Go to django_rest and create the virtual environment env

virtualenv env
Copy the code

Activate the virtual environment and install Django

source ./env/bin/activate
Copy the code

Install django

pip install django
Copy the code

Create rest_app

python manage.py startapp rest_app
Copy the code

Register the app and add the app to INSTALLED_APPS

#setting.py

INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'rest_app'
]

Copy the code

Create the admin account for management

$ python manage.py createsuperuser

Username (leave blank to use 'root'):admin 
Email address: 
Password: 
Password (again): 
Superuser created successfully.
Copy the code

2. Create ORM models

Sqlite3 is the default database. If you need to change databases, you can configure databases in setting.py.

Modify our /django_rest/models.py to add our man model

#models.py

from django.db import models



# Create your models here.
class Man(models.Model) :
    name = models.CharField(max_length=64)
    sex = models.CharField(max_length=64)

    def __str__(self) :
        return self.name

Copy the code

Do database migration

python manage.py makemigrations 
python manage.py migrate
Copy the code

To register the Man model in our backend so that we can add, delete, and modify django’s backend, write admin.py as follows

#admin.py
from django.contrib import admin
from .models import Man
# Register your models here.

admin.site.register(Man)  # Register Man to background
Copy the code

Starting Django Services

python manage.py runserver
Copy the code

Visit http://127.0.0.1:8000/admin/ you can see the login interface, enter the password to log in

You can see the model MAN object mans under our rest_app

Let’s add a lgD.ame for that man


3. Load the Django REST Framework

Install toolkit

pip install djangorestframework
Copy the code

Registered rest_framework

#setting.py
INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'rest_app'
    'rest_framework' # registered
]
Copy the code
4. Serialization model

The serializer converts (serializes) our model data into JSON format so that it can be requested. Also, when joSN data is submitted, the serializer will convert the JSON data into a model for us to use.

We create the file serializer.py under rest_app

We’re going to do three things:

  1. Import Man model
  2. Import sequence REST Framework serializer
  3. Create a new class to link the model to the serializer
from rest_framework import serializers

from .models import Man

class Manserializer(serializers.HyperlinkedModelSerializer) :
    class Meta:
        model = Man
        fields = ('name'.'sex')

Copy the code
5. Create the view and URL to load the data

We need to return the serialized data to the browser, so we need to do the following:

  1. The database was queried through the invalid Man. Procedure
  2. The queried data is passed to the serializer, which converts it into JSON

We write our views in rest_app/views.py. ModelViewSet is provided by the Rest_framework and contains get and POST methods

# views.py
from rest_framework import viewsets

from .serializers import ManSerializer
from .models import Man


class ManViewSet(viewsets.ModelViewSet) :
    queryset = Man.objects.all().order_by('name')  Query results to querySet
    serializer_class = ManSerializer     # Serialize the result
Copy the code

Add API routing to urls.py in the django_rest directory

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path(' ', include('rest_app.urls')),]Copy the code

In the rest_app directory, create urls.py and add a view route, using the Router in the Rest_framework to ensure that our requests go to the correct dynamic resource.

from django.urls import include, path
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'man', views.ManViewSet)   Route to the ManViewSet view

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path(' ', include(router.urls)), # Use router routing
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')))Copy the code

Finally, let’s start the service. Visit http://127.0.0.1:8000/ and you can view our API information in your browser

python manage.py runserver
Copy the code

Visit http://127.0.0.1:8000/man/ to view the man resources

By id to access the API resources at http://127.0.0.1:8000/man/1/


This completes the creation of a basic restful style API. The key point is to understand the ModelViewSet and the built-in Router and not read the source code to know why.


Feel free to point out any shortcomings in this article in the comments section.

Welcome to collect, like and ask questions. Keep an eye on top water cooler managers and sometimes do more than just boil hot water.