Django Rest Framework Token Authentication

Adi Ramadhan
2 min readJul 17, 2020

--

Create DRF REST API with Token Authentication.
Official docs here.

Step 1: Preparation, Create Django Project, Initial Migration
Install virtualenv: pip install virtualenv
Create virtualenv: virtualenv venv
Start virtualenv: venv/Scripts/activate
Install Django, DRF in virtualenv: pip install django djangorestframework
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Initial Migration: python manage.py migrate
Create superuser: python manage.py createsuperuser
(for example: username=admin)

Step 2: Create App
Create app: python manage.py createapp myapp
Create API in myapp/views.py

myapp/views.py

Step 3: Set up urls
Create myapp/urls.py

myapp/urls.py

Update myproject/urls.py

Step 4: Settings.py

Register myapp, rest_framework and rest_framework.authtoken in INSTALLED_APPS

INSTALLED_APPS in settings.py

Add REST_FRAMEWORK in myproject/settings.py

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # new
],
}

Step 5: Migrate
Migrate rest framework model: python manage.py migrate

Step 6: Testing
Generate token for user admin for testing purpose:
python manage.py drf_create_token admin

Generated token for user admin

Run server: python manage.py runserver

Test call API using POSTMAN. Download and see official docs here.
http://127.0.0.1:8000/hello/
Header
Authorization: Token <token>

--

--