Home > OS >  Python Requests with Django Rest Framework - 'detail': 'Authentication credentials we
Python Requests with Django Rest Framework - 'detail': 'Authentication credentials we

Time:12-03

I've got a tiny function that just looks to get a response from my DRF API Endpoint.

My DRF settings look like this:

    "DEFAULT_AUTHENTICATION_CLASSES": [
        # Enabling this it will require Django Session (Including CSRF)
        "rest_framework.authentication.SessionAuthentication"
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        # Globally only allow IsAuthenticated users access to API Endpoints
        "rest_framework.permissions.IsAuthenticated"
    ],

I'm using this to try and hit the endpoint:

def get_car_details(car_id):
    headers = {"X-Requested-With": "XMLHttpRequest"}
    api_app = "http://localhost:8000/"
    api_model = "cars/"
    response = requests.get(api_app   api_model   str(car_id), headers=headers)
    json_response = response.json()
    return json_response

I keep getting 'detail': 'Authentication credentials were not provided'

Do I need to generate a CSRF token and include it in a GET request? The only time this gets hit is when a user goes to a view that requires they are logged in. Is there a way to pass that logged-in user to the endpoint??

CodePudding user response:

When you make your request from the get_car_details function you need to be sure that the request is authenticated. This does not look like a CSRF issue.

When using session based authentication a session cookie is passed back after logging in. So before you call get_car_details you would need to first make a request to login, keep that session, and use that session when calling the API.

Requests has a session class requests.Session() that you can use for this purpose. Details here: https://docs.python-requests.org/en/latest/user/advanced/

Many people find token based authentication easier partly a session cookie does not need to be maintained.

  • Related