第一部分:应用基础
并启动Django的开发服务器。
python manage.py runserver
Validating models...
0 errors found
Django 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 JSON
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
或通过添加格式后缀:
http http://127.0.0.1:8000/snippets.json # JSON suffix
http http://127.0.0.1:8000/snippets.api # Browsable API suffix
同样,我们可以使用Content-Type
标头来控制发送的请求的格式。
# POST using form data
http --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 JSON
http --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
请求中添加了一个开关,您将能够在请求标题中看到请求类型。
补充部分
对于在我们的网址中添加可选的格式后缀,我会在下篇文章中进行阐述