Authenticating with the API

Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.

When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.

If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.

If we try to create a snippet without authenticating, we'll get an error:

  1. http POST http://127.0.0.1:8000/snippets/ code="print(123)"
  2. {
  3. "detail": "Authentication credentials were not provided."
  4. }

We can make a successful request by including the username and password of one of the users we created earlier.

  1. http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
  2. {
  3. "id": 1,
  4. "owner": "admin",
  5. "title": "foo",
  6. "code": "print(789)",
  7. "linenos": false,
  8. "language": "python",
  9. "style": "friendly"
  10. }