Testing our first attempt at a Web API

Now we can start up a sample server that serves our snippets.

Quit out of the shell…

  1. quit()

…and start up Django's development server.

  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.

In another terminal window, we can test the server.

We can test our API using curl or httpie. Httpie is a user friendly http client that's written in Python. Let's install that.

You can install httpie using pip:

  1. pip install httpie

Finally, we can get a list of all of the snippets:

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

Or we can get a particular snippet by referencing its 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. }

Similarly, you can have the same json displayed by visiting these URLs in a web browser.