How's it looking?

Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

We can get a list of all of the snippets, as before.

  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. ]

We can control the format of the response that we get back, either by using the Accept header:

  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

Or by appending a format suffix:

  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

Similarly, we can control the format of the request that we send, using the Content-Type header.

  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. }

If you add a —debug switch to the http requests above, you will be able to see the request type in request headers.

Now go and open the API in a web browser, by visiting http://127.0.0.1:8000/snippets/.

Browsability

Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.

Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.

See the browsable api topic for more information about the browsable API feature and how to customize it.