a4c3e343ca60d6411ce1cddbc698b10f.jpg


第一部分:应用基础

并启动Django的开发服务器。

  1. python manage.py runserver
  2. Validating models...
  3. 0 errors found
  4. Django version 1.11, using settings 'tutorial.settings'
  5. Development server is running at http://127.0.0.1:8000/
  6. Quit the server with CONTROL-C.

在另一个终端窗口中,我们可以测试服务器。
我们可以使用curlhttpie测试我们的API 。Httpie是使用Python编写的用户友好型HTTP客户端。让我们安装它。
您可以使用pip安装httpie:

  1. pip install httpie

最后,我们可以获得所有代码段的列表:

  1. http http://127.0.0.1:8000/snippets/
  2. HTTP/1.1 200 OK
  3. ...
  4. [
  5. {
  6. "id": 1,
  7. "title": "",
  8. "code": "foo = \"bar\"\n",
  9. "linenos": false,
  10. "language": "python",
  11. "style": "friendly"
  12. },
  13. {
  14. "id": 2,
  15. "title": "",
  16. "code": "print(\"hello, world\")\n",
  17. "linenos": false,
  18. "language": "python",
  19. "style": "friendly"
  20. }
  21. ]

或者,我们可以通过引用其ID来获取特定的代码段:

  1. http http://127.0.0.1:8000/snippets/2/
  2. HTTP/1.1 200 OK
  3. ...
  4. {
  5. "id": 2,
  6. "title": "",
  7. "code": "print(\"hello, world\")\n",
  8. "linenos": false,
  9. "language": "python",
  10. "style": "friendly"
  11. }

同样,通过在Web浏览器中访问这些URL,可以显示相同的json。


第二部分:基础扩展

和以前一样,我们可以获得所有代码片段的列表。

  1. http http://127.0.0.1:8000/snippets/
  2. HTTP/1.1 200 OK
  3. ...
  4. [
  5. {
  6. "id": 1,
  7. "title": "",
  8. "code": "foo = \"bar\"\n",
  9. "linenos": false,
  10. "language": "python",
  11. "style": "friendly"
  12. },
  13. {
  14. "id": 2,
  15. "title": "",
  16. "code": "print(\"hello, world\")\n",
  17. "linenos": false,
  18. "language": "python",
  19. "style": "friendly"
  20. }
  21. ]

我们可以通过使用Accept标头来控制返回的响应的格式:

  1. http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
  2. http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML

或通过添加格式后缀:

  1. http http://127.0.0.1:8000/snippets.json # JSON suffix
  2. http http://127.0.0.1:8000/snippets.api # Browsable API suffix

同样,我们可以使用Content-Type标头来控制发送的请求的格式。

  1. # POST using form data
  2. http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
  3. {
  4. "id": 3,
  5. "title": "",
  6. "code": "print(123)",
  7. "linenos": false,
  8. "language": "python",
  9. "style": "friendly"
  10. }
  11. # POST using JSON
  12. http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
  13. {
  14. "id": 4,
  15. "title": "",
  16. "code": "print(456)",
  17. "linenos": false,
  18. "language": "python",
  19. "style": "friendly"
  20. }

如果您--debug在上述http请求中添加了一个开关,您将能够在请求标题中看到请求类型。

补充部分

对于在我们的网址中添加可选的格式后缀,我会在下篇文章中进行阐述