
第一部分:应用基础
并启动Django的开发服务器。
python manage.py runserverValidating models...0 errors foundDjango version 1.11, using settings 'tutorial.settings'Development server is running at http://127.0.0.1:8000/Quit the server with CONTROL-C.
在另一个终端窗口中,我们可以测试服务器。
我们可以使用curl或httpie测试我们的API 。Httpie是使用Python编写的用户友好型HTTP客户端。让我们安装它。
您可以使用pip安装httpie:
pip install httpie
最后,我们可以获得所有代码段的列表:
http http://127.0.0.1:8000/snippets/HTTP/1.1 200 OK...[{"id": 1,"title": "","code": "foo = \"bar\"\n","linenos": false,"language": "python","style": "friendly"},{"id": 2,"title": "","code": "print(\"hello, world\")\n","linenos": false,"language": "python","style": "friendly"}]
或者,我们可以通过引用其ID来获取特定的代码段:
http http://127.0.0.1:8000/snippets/2/HTTP/1.1 200 OK...{"id": 2,"title": "","code": "print(\"hello, world\")\n","linenos": false,"language": "python","style": "friendly"}
同样,通过在Web浏览器中访问这些URL,可以显示相同的json。
第二部分:基础扩展
和以前一样,我们可以获得所有代码片段的列表。
http http://127.0.0.1:8000/snippets/HTTP/1.1 200 OK...[{"id": 1,"title": "","code": "foo = \"bar\"\n","linenos": false,"language": "python","style": "friendly"},{"id": 2,"title": "","code": "print(\"hello, world\")\n","linenos": false,"language": "python","style": "friendly"}]
我们可以通过使用Accept标头来控制返回的响应的格式:
http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSONhttp http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
或通过添加格式后缀:
http http://127.0.0.1:8000/snippets.json # JSON suffixhttp http://127.0.0.1:8000/snippets.api # Browsable API suffix
同样,我们可以使用Content-Type标头来控制发送的请求的格式。
# POST using form datahttp --form POST http://127.0.0.1:8000/snippets/ code="print(123)"{"id": 3,"title": "","code": "print(123)","linenos": false,"language": "python","style": "friendly"}# POST using JSONhttp --json POST http://127.0.0.1:8000/snippets/ code="print(456)"{"id": 4,"title": "","code": "print(456)","linenos": false,"language": "python","style": "friendly"}
如果您--debug在上述http请求中添加了一个开关,您将能够在请求标题中看到请求类型。
补充部分
对于在我们的网址中添加可选的格式后缀,我会在下篇文章中进行阐述
