djangorestframework-api-key

3.1.0 · active · verified Sat Apr 11

djangorestframework-api-key (DRF API Key) is a Django REST Framework library providing API key permissions for server-side clients. It allows secure interaction for machines or third-party services that do not have user accounts, focusing on authorization rather than user authentication. The current version is 3.1.0, and it maintains a regular release cadence with several updates annually, supporting recent Django and Python versions.

Warnings

Install

Imports

Quickstart

To get started, add `rest_framework_api_key` to your `INSTALLED_APPS` in `settings.py` and run migrations. Then, configure `HasAPIKey` as a default permission class in `REST_FRAMEWORK` settings or apply it to individual views. Clients will then need to provide the generated API key in the `Authorization: Api-Key <API_KEY>` header. API keys can be created via the Django admin panel or programmatically using `APIKey.objects.create_key()`. The full key is only visible upon creation; subsequently, only its prefix is shown for security.

import os

# settings.py
INSTALLED_APPS = [
    # ...
    'rest_framework',
    'rest_framework_api_key',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework_api_key.permissions.HasAPIKey'
    ]
}

# --- Example usage in a Django REST Framework view ---

# In your_app/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_api_key.permissions import HasAPIKey
from rest_framework_api_key.models import APIKey

class ProtectedView(APIView):
    permission_classes = [HasAPIKey]

    def get(self, request, format=None):
        # You can access the APIKey object associated with the request
        api_key = request.user # In this library, `request.user` is the APIKey instance
        return Response({
            "message": f"Hello, API Key client! Key name: {api_key.name}"
        })

# To create an API key programmatically (e.g., in a management command or shell):
# from rest_framework_api_key.models import APIKey
# api_key_obj, key = APIKey.objects.create_key(name="My Service Key")
# print(f"New API Key: {key}") # This is the ONLY time the full key is shown!
# Ensure you store this 'key' value securely and provide it to your client.

# Example of how a client would use this key:
# Authorization: Api-Key <THE_GENERATED_KEY>

view raw JSON →