Skip to content
Advertisement

How to test authenticated POST request with Pytest in Django

I want to test an authenticated post request on an API using Pytest. This is what I am doing so far:

JavaScript

This doesn’t work because it gives me back a 401 (Unauthorized) instead of a 200. That makes sense since the fixture is a client and not an admin client.

Yet if I pass in admin_client instead of client it gives me a Bad Request. The data that I send should be fine though.

I also tried to pass in the headers like so (since I use JWT authorization):

JavaScript

Finally I tried to log in before which gives me a 403 (Forbidden):

JavaScript

If someone could point me into the right direction that would be fantastic! Thanks a lot in advance

Advertisement

Answer

You can hit the login url with username and password and get the token. creade a header dictionary like headers = {'Authorization': 'JWT <token>'}

and use the header when using post.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement