Enabling CORS on Django REST Framework

Defining the CORS Problem

First, let’s outline the browser security policy that creates this issue. CORS is enforced by web browsers to prevent malicious sites from accessing resources on other sites without authorization. Therefore, when a web app served from example.com tries to access an API at api.example.com, the browser blocks the request unless the API explicitly enables CORS.

Fortunately, Django REST Framework provides ways to configure your API to allow cross-origin requests. We will explore some options, from simple to robust, to make your API accessible.

Using CORS Middleware

Next, we will try the fastest way to enableCORS using a middleware class. Middleware offers a simple way to execute logic on every request and response in Django.

To begin, install django-cors-headers:

pip install django-cors-headers

Allowing Specific Origins

For more control over CORS, you can specify the allowed origins instead of enabling it globally.

The CORS middleware includes an CORS_ALLOW_ALL_ORIGINS setting. To allow specific origins only, add the CORS_ALLOWED_ORIGINS setting instead:

CORS_ALLOW_ALL_ORIGINS = False

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",  
]

Advanced Configuration with CORS Classes

For the most flexibility, Django REST Framework includesCORS classes to override per view or viewset. This grants you control of theCORS headers on a granular level.

To begin, remove theCORS middleware from the settings since the classes replace it. Then in any view or viewset, enableCORS with:

from rest_framework.decorators import permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    permission_classes = [AllowAny]

    def get(self, request):
        content = {
            'message': 'Hello, World!'
        }
        return Response(content)

Conclusion

In summary, enablingCORS in Django REST Framework prevents cross-origin errors that block API access. The middleware provides a shortcut, whileCORS settings and classes deliver more granular control. Consider your requirements to determine the best solution – your application architecture may benefit from different configurations per endpoint. With these options, you can securely open your web APIs to external web apps.