使用Django开发REST 接口

我们以在Django框架中使用的图书英雄案例来写一套支持图书数据增删改查的REST API接口,来理解REST API的开发。

在此案例中,前后端均发送JSON格式数据。

# views.py

from django.views.generic import View
from book.models import BookInfo
from django.http import JsonResponse,HttpResponse
import json

# Create your views here.
class BookListView(View):
    """
    查询所有图书、增加图书
    """
    def get(self, request):
        """
        查询所有图书
        路由:GET /books/
        """
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id': book.id,
                'name': book.name,
                'pub_date': book.pub_date
            })
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        """
        新增图书
        路由:POST /books/
        """
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book = BookInfo.objects.create(
            name=book_dict.get('name'),
            pub_date=book_dict.get('pub_date')
        )

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        },safe=False)

class BookDetailView(View):
    """
    获取单个图书信息
    修改图书信息
    删除图书
    """
    def get(self, request, pk):
        """
        获取单个图书信息
        路由: GET  /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def put(self, request, pk):
        """
        修改图书信息
        路由: PUT  /books/<pk>
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)

        # 此处详细的校验参数省略

        book.name = book_dict.get('name')
        book.pub_date = book_dict.get('pub_date')
        book.save()

        return JsonResponse({
            'id': book.id,
            'name': book.name,
            'pub_date': book.pub_date
        })

    def delete(self, request, pk):
        """
        删除图书
        路由: DELETE /books/<pk>/
        """
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return JsonResponse({},status=404)

        book.delete()

        return JsonResponse({},status=204)
from django.urls import path
from book.views import BookListView,BookDetailView

urlpatterns = [
    path('books/',BookListView.as_view()),
    path('books/<int:pk>/', BookDetailView.as_view()),
]

测试

使用Postman测试上述接口

1) 获取所有图书数据

GET 方式访问http://127.0.0.1:8000/books/,返回状态码200,数据如下

[
    {
        "id": 2,
        "commentcount": 40,
        "pub_date": "1986-07-24",
        "readcount": 36,
        "name": "天龙八部",
        "image": ""
    },
    {
        "id": 3,
        "commentcount": 18,
        "pub_date": "1995-12-24",
        "readcount": 28,
        "name": "笑傲江湖",
        "image": ""
    },
    {
        "id": 4,
        "commentcount": 24,
        "pub_date": "1987-11-11",
        "readcount": 58,
        "name": "雪山飞狐",
        "image": ""
    },
    {
        "id": 5,
        "commentcount": 0,
        "pub_date": "2000-05-01",
        "readcount": 0,
        "name": "新射雕英雄传",
        "image": ""
    },
    {
        "id": 6,
        "commentcount": 0,
        "pub_date": "1990-05-01",
        "readcount": 0,
        "name": "射雕英雄传",
        "image": ""
    }
]

2)获取单一图书数据

GET 访问http://127.0.0.1:8000/books/2/,返回状态码200, 数据如下

{
    "id": 2,
    "commentcount": 40,
    "pub_date": "1986-07-24",
    "readcount": 36,
    "name": "天龙八部",
    "image": ""
}

GET 访问http://127.0.0.1:8000/books/100/,返回状态码404

3)新增图书数据

POST 访问http://127.0.0.1:8000/books/ ,发送JSON数据

{

    "pub_date": "1990-05-01",
    "name": "python入门"
}

返回状态码201,数据如下

{
    "id": 7,
    "commentcount": 0,
    "pub_date": "1990-05-01",
    "readcount": 0,
    "name": "python入门",
    "image": ""
}

4)修改图书数据

PUT 访问http://127.0.0.1:8000/books/7/,发送JSON数据

{

    "pub_date": "1990-05-01",
    "name": "python高级"
}

返回状态码200,数据如下

{
    "id": 7,
    "commentcount": 0,
    "pub_date": "1990-05-01",
    "readcount": 0,
    "name": "python高级",
    "image": ""
}

5)删除图书数据

DELETE 访问http://127.0.0.1:8000/books/7/,返回204状态