To be able to work with Django framework, first we have to install it on our windows system. Python is a prerequisite for Django installation. If python is not installed on your system, first install python. Next run the following command on a command-prompt window for creating a virtual environment
Django Rest Framework (DRF)It provides the foundational tools for building APIs in Django, including: Serialization, Views and ViewSets, Routing, Authentication and Permissions, Browsable API.
To work with it, first of all you have to install DRF package. DRF package do not come with django by default.
pip install djangorestframework
Next add it to the INSTALLED APPS section of your settings.py
INSTALLED_APPS = [
'rest_framework'
]
Now your django project is ready to handle the REST API views and serializers.
Why use DRF?
-> Without DRF you would have to write all JSON handling manually with JsonResponse and class-based view, which is a much slower process.
Now, you will need something to work with the authentication. Here comes a third-party library "djangorestframework-simplejwt". It provides a specific type of authentication for DRF.
Cross-Origin Resource Sharing
Django CORS Headers
pip install django-cors-headers
Next into settings.py add:
INSTALLED_APPS [
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # make sure it is on top of CommonMiddleware
]
CORS_ALLOW_ALL_ORIGINS = True # use it for testing purpose only
# safer version is
CORS_ALLOWED-ORIGINS = [
"http://localhost:3000", # the site you want to allow
]
CSRF Protection (if using session auth)
If your API view isn't exempt from CSRF, Django may reject POST requests.
While using DRF, best is to use APIView/ViewSets with REST framework authentication, or add:
@csrf_exempt
def view(...):
. . .
(for testing only -- better configure proper auth later).