Django RESTFul (interface application)

Posted by andyhajime on Sun, 12 Jan 2020 12:20:50 +0100

Django interface application

Written in front

  • RESTFul is a unified interface principle. For specific explanation, please refer to the following connection
  • The interface view function only returns the JSON type to the front-end, and then gives the JSON data to js, so that the front-end js can handle the html page changes

1. Try to write an interface

1.1 new django project

If you have created a new project (including mysql database) and it can run successfully
You can skip 1.1 and go to 1.2

1.1.1. First, create a new django project in pycharm

(here I use Python 3, django2)

django 0 foundation can read this article first, and then read the following:

Remember to modify the setting configuration file after creation (DEBUG = True, allowed ENU hosts = ["*"], change the database to mysql, and comment out the csrf)

1.1.2 write driver (used to connect mysql)

1.1.3 new database

Input instruction, log in database

Login database instruction: mysql -u user name - p password

Building database

create database Library name charset=utf8;

1.1.4 migration

Execute migration command

python migrate

I used django2 here, so I reported an error. This problem is only caused by django2

Specific solution: find the line below if version corresponding to the base file below, comment it out and write a pass

Execute migration command again, successful

1.1.5 login database

Here we log in pycharm (you can also log in navicat and other database software)

Note that the name of the database should be consistent with the name of the database created in 1.1.3

Then fill in the user name and password

Fill in the information point test connection, as shown in the figure above. If the green part is checked, you can click "ok",

If the test fails

For database version, please refer to
Refer to the database time zone:

Create success

1.2 first test whether django can start normally

python runserver

Enter in the browser, and the following page will run successfully

1.3 create interface application

1.3.1 create application Api

According to RESTFul principle, we should call the interface application "Api"“

python startapp Api

Remember to register Api in setting after creation (error may be reported when using without registration)

Create a new in Api

Add the new on the root route untitled/

Note: This is the way django2 is written. django1 is slightly different

Add a route in Api/

Create corresponding view function in view

1.4 operation and access


Then try to access the interface in the browser

Here a simple django interface is created successfully

2. Use interface

2.1. Use the postman tool to send a POST request

2.1.1 download postman (interface test tool)

Open postman and it will pop up a login page, which can be skipped directly

You can refer to this article for the post man tutorial (I don't think it's necessary, it's easy to operate)

2.1.2 write an interface that can receive post requests

Api routing

Model (

from django.db import models

# Create your models here.
class Book(models.Model):
    b_name = models.CharField(max_length=32)
    b_price = models.FloatField(default=1.0)

    def to_dict(self):
        return {'id':, 'b_name': self.b_name, 'b_price': self.b_price}


python makemigrations
python migrate


from Api.models import Book
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

def books(request):
    if request.method == "GET":
    if request.method == "POST":
        b_name = request.POST.get('b_name')
        b_price = request.POST.get('b_price')

        book = Book()
        book.b_name = b_name
        book.b_price = b_price
        data = {
            "status": 201,
            "data": book.to_dict(),
        return JsonResponse(data=data)

2.1.3 open postman and send a POST request

Start django first

python runserver

Open postman and input the corresponding content

Click send to send and the following screenshot will show success

You can also check whether the data is inserted in the database

2.1.4. There are also interface testing tools under the linux command window

Students using the linux command window can view this article
HTTPie installation and use:

POST request simulating form

http -f POST b_name='java book' b_price=20

Common operation instructions:

http -f POST name=name  #Simulation form submission

http -v     #Show detailed request information
http -h,com     #Show headers only
http -b     #Show Body only
http -d     #Download File

http PUT name=name password=pwd  #Pass json type parameter (string)
http PUT age:=28 #Non string type use:=Division

http --form POST name='name'    #Simulated formPOSTrequest
http -f POST  name='name' file@~/test.txt  #Upload simulation form file

http User-Agent:Txl/1.0 'Cookie:a=b;b=c' Referer:
# Modify request header using: split

http -a username:password   #Authentication
http --auth--type=digest -a user:pwd  #Authentication

http --proxy=http:
# UseHTTPagent

2.2 GET request


    if request.method == "GET":
        book_list = Book.objects.all()
        book_list_json = []
        for book in book_list:
        data = {
            "status": 200,
            "data": book_list_json,
        return JsonResponse(data=data)

Start django

Request in postman

2.3 GET request with parameters

Get a Book


def book(request, bookid):
    if request.method == "GET":
        book_obj = Book.objects.get(pk=bookid)
        data = {
            "status": 200,
            "data": book_obj.to_dict(),
        return JsonResponse(data=data)


2.4 DELETE request with parameters



3. Interface and web page docking

Create static folder

Registered static

3.1. Create a new BookList.html

First import jQuery (. JS and. min.js are copied in)

jq Download address:

New BookList.html

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>List of books</title>
    // If you copy directly, pay attention to your jquery location and name, which may be inconsistent with mine
    <script type="text/javascript" src="/static/js/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $.getJSON("/api/books/", function (data) {
                if (data['status'] === 200) {
                    var $ul = $("ul");
                    var books = data['data'];
                    for (var i = 0; i < books.length; i++) {
                        var $li = $("<li></li>");



<div id="container">


Here $. getJSON("/api/books /" Get the json data directly from the view books

3.2 browser access

Post run access: note that this is a direct access html file without routing allocation (html obtains json data through jq asynchronous submission)

87 original articles published, 20 praised, 1578 visited
Private letter follow

Topics: Database Django Python MySQL