1. [
  1. 课程介绍
  2. ](_index_)
    1. [
  1. 引入DjangoRESTframework
  2. ](c01-introducetodrf_index)
  3. -
  4. [
  5. Web应用模式
  6. ](c01-introducetodrf_separatedfrontendandbackend)
    1. [
  1. 认识RESTful
  2. ](c01-introducetodrf_introducetorest)
    1. [
  1. RESTful设计方法
  2. ](c01-introducetodrf_howtodesignrest)
    1. [
  1. 使用Django开发REST接口
  2. ](c01-introducetodrf_developrestapiwithdjango)
    1. [
  1. 明确REST接口开发的核心任务
  2. ](c01-introducetodrf_coretasktodeveloprestapi)
    1. [
  1. DjangoRESTframework简介
  2. ](c01-introducetodrf_aboutdrf)
    1. [
  1. DRF工程搭建
  2. ](c02-drfproject_index)
  3. -
  4. [
  5. 环境安装与配置
  6. ](c02-drfproject_installandconfig)
    1. [
  1. 见识DRF的魅力
  2. ](c02-drfproject_thefirstdrfprogram)
    1. [
  1. Serializer序列化器
  2. ](c03-serializer_index)
  3. -
  4. [
  5. 定义Serializer
  6. ](c03-serializer_declaring)
    1. [
  1. 序列化使用
  2. ](c03-serializer_serializing)
    1. [
  1. 反序列化使用
  2. ](c03-serializer_deserializing)
    1. [
  1. 模型类序列化器ModelSerializer
  2. ](c03-serializer_modelserializer)
    1. [
  1. 视图
  2. ](c04-view_index)
  3. -
  4. [
  5. RequestResponse
  6. ](c04-view_requestandresponse)
    1. [
  1. 视图概览
  2. ](c04-view_view)
    1. [
  1. 视图说明
  2. ](c04-view_viewintroduction)
    1. [
  1. 视图集ViewSet
  2. ](c04-view_viewset)
    1. [
  1. 路由Router
  2. ](c04-view_routers)
    1. [
  1. 其他功能
  2. ](c05-components_index)
  3. -
  4. [
  5. 认证
  6. ](c05-components_authentication)
    1. [
  1. 权限
  2. ](c05-components_permissions)
    1. [
  1. 限流
  2. ](c05-components_throttling)
    1. [
  1. 过滤
  2. ](c05-components_filtering)
    1. [
  1. 排序
  2. ](c05-components_ordering)
    1. [
  1. 分页
  2. ](c05-components_pagination)
    1. [
  1. 版本
  2. ](c05-components_versioning)
    1. [
  1. 异常处理
  2. ](c05-components_exceptions)
    1. [
  1. 自动生成接口文档
  2. ](c05-components_documents)
    1. [
    2. Published with GitBook
    3. ](https://www.gitbook.com)

课程介绍

使用Django开发REST 接口

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

  1. # views.py
  2. from datetime import datetime
  3. class BooksAPIVIew(View):
  4. """
  5. 查询所有图书、增加图书
  6. """
  7. def get(self, request):
  8. """
  9. 查询所有图书
  10. 路由:GET /books/
  11. """
  12. queryset = BookInfo.objects.all()
  13. book_list = []
  14. for book in queryset:
  15. book_list.append({
  16. 'id': book.id,
  17. 'btitle': book.btitle,
  18. 'bpub_date': book.bpub_date,
  19. 'bread': book.bread,
  20. 'bcomment': book.bcomment,
  21. 'image': book.image.url if book.image else ''
  22. })
  23. return JsonResponse(book_list, safe=False)
  24. def post(self, request):
  25. """
  26. 新增图书
  27. 路由:POST /books/
  28. """
  29. json_bytes = request.body
  30. json_str = json_bytes.decode()
  31. book_dict = json.loads(json_str)
  32. # 此处详细的校验参数省略
  33. book = BookInfo.objects.create(
  34. btitle=book_dict.get('btitle'),
  35. bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
  36. )
  37. return JsonResponse({
  38. 'id': book.id,
  39. 'btitle': book.btitle,
  40. 'bpub_date': book.bpub_date,
  41. 'bread': book.bread,
  42. 'bcomment': book.bcomment,
  43. 'image': book.image.url if book.image else ''
  44. }, status=201)
  45. class BookAPIView(View):
  46. def get(self, request, pk):
  47. """
  48. 获取单个图书信息
  49. 路由: GET /books/<pk>/
  50. """
  51. try:
  52. book = BookInfo.objects.get(pk=pk)
  53. except BookInfo.DoesNotExist:
  54. return HttpResponse(status=404)
  55. return JsonResponse({
  56. 'id': book.id,
  57. 'btitle': book.btitle,
  58. 'bpub_date': book.bpub_date,
  59. 'bread': book.bread,
  60. 'bcomment': book.bcomment,
  61. 'image': book.image.url if book.image else ''
  62. })
  63. def put(self, request, pk):
  64. """
  65. 修改图书信息
  66. 路由: PUT /books/<pk>
  67. """
  68. try:
  69. book = BookInfo.objects.get(pk=pk)
  70. except BookInfo.DoesNotExist:
  71. return HttpResponse(status=404)
  72. json_bytes = request.body
  73. json_str = json_bytes.decode()
  74. book_dict = json.loads(json_str)
  75. # 此处详细的校验参数省略
  76. book.btitle = book_dict.get('btitle')
  77. book.bpub_date = datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
  78. book.save()
  79. return JsonResponse({
  80. 'id': book.id,
  81. 'btitle': book.btitle,
  82. 'bpub_date': book.bpub_date,
  83. 'bread': book.bread,
  84. 'bcomment': book.bcomment,
  85. 'image': book.image.url if book.image else ''
  86. })
  87. def delete(self, request, pk):
  88. """
  89. 删除图书
  90. 路由: DELETE /books/<pk>/
  91. """
  92. try:
  93. book = BookInfo.objects.get(pk=pk)
  94. except BookInfo.DoesNotExist:
  95. return HttpResponse(status=404)
  96. book.delete()
  97. return HttpResponse(status=204)
  1. # urls.py
  2. urlpatterns = [
  3. url(r'^books/$', views.BooksAPIVIew.as_view()),
  4. url(r'^books/(?P<pk>\d+)/$', views.BookAPIView.as_view())
  5. ]

测试

使用Postman测试上述接口
1) 获取所有图书数据
GET 方式访问 http://127.0.0.1:8000/books/, 返回状态码200,数据如下

  1. [
  2. {
  3. "id": 1,
  4. "btitle": "射雕英雄传",
  5. "bpub_date": "1980-05-01",
  6. "bread": 12,
  7. "bcomment": 34,
  8. "image": ""
  9. },
  10. {
  11. "id": 2,
  12. "btitle": "天龙八部",
  13. "bpub_date": "1986-07-24",
  14. "bread": 36,
  15. "bcomment": 40,
  16. "image": ""
  17. },
  18. {
  19. "id": 3,
  20. "btitle": "笑傲江湖",
  21. "bpub_date": "1995-12-24",
  22. "bread": 20,
  23. "bcomment": 80,
  24. "image": ""
  25. },
  26. {
  27. "id": 4,
  28. "btitle": "雪山飞狐",
  29. "bpub_date": "1987-11-11",
  30. "bread": 58,
  31. "bcomment": 24,
  32. "image": ""
  33. },
  34. {
  35. "id": 5,
  36. "btitle": "西游记",
  37. "bpub_date": "1988-01-01",
  38. "bread": 10,
  39. "bcomment": 10,
  40. "image": "booktest/xiyouji.png"
  41. },
  42. {
  43. "id": 6,
  44. "btitle": "水浒传",
  45. "bpub_date": "1992-01-01",
  46. "bread": 10,
  47. "bcomment": 11,
  48. "image": ""
  49. },
  50. {
  51. "id": 7,
  52. "btitle": "红楼梦",
  53. "bpub_date": "1990-01-01",
  54. "bread": 0,
  55. "bcomment": 0,
  56. "image": ""
  57. }
  58. ]

2)获取单一图书数据
GET 访问 http://127.0.0.1:8000/books/5/ ,返回状态码200, 数据如下

  1. {
  2. "id": 5,
  3. "btitle": "西游记",
  4. "bpub_date": "1988-01-01",
  5. "bread": 10,
  6. "bcomment": 10,
  7. "image": "booktest/xiyouji.png"
  8. }

GET 访问http://127.0.0.1:8000/books/100/,返回状态码404
3)新增图书数据
POST 访问http://127.0.0.1:8000/books/,发送JSON数据:

  1. {
  2. "btitle": "三国演义",
  3. "bpub_date": "1990-02-03"
  4. }

返回状态码201,数据如下

  1. {
  2. "id": 8,
  3. "btitle": "三国演义",
  4. "bpub_date": "1990-02-03",
  5. "bread": 0,
  6. "bcomment": 0,
  7. "image": ""
  8. }

4)修改图书数据
PUT 访问http://127.0.0.1:8000/books/8/,发送JSON数据:

  1. {
  2. "btitle": "三国演义(第二版)",
  3. "bpub_date": "1990-02-03"
  4. }

返回状态码200,数据如下

  1. {
  2. "id": 8,
  3. "btitle": "三国演义(第二版)",
  4. "bpub_date": "1990-02-03",
  5. "bread": 0,
  6. "bcomment": 0,
  7. "image": ""
  8. }

5)删除图书数据
DELETE 访问http://127.0.0.1:8000/books/8/,返回204状态码