Python – How to create a login API using Django Rest Framework

djangodjango-rest-frameworkpythonrest

I want to create a login api (or use an existing one if it is already pre-bundled) using django rest framework. However, I'm completely at a loss. Whenever I send a post request to the django rest framework "login" url, it just sends back the browsable api template page…

MY CONFIGURATION

urls.py

url(r'^api/v1/', include('rest_framework.urls', namespace='rest_framework'))

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

WHAT I WANT

Request:

POST /api/v1/login  username='name' pass='pass'

Response:

200 OK "{username: 'name', 'userId': '54321'}" set-cookie: sessionid="blahblah"

Best Answer

Take a look at the api view from django-rest-framework-jwt. It's an implementation for creating auth tokens rather than cookie sessions, but your implementation will be similar. See views.py and serializers.py. You can probably use the serializers.py unchanged, and just adjust your views to return the right parameters and possibly set the session cookie (can't recall if that's already performed in authentication).

Related Topic