An API key is a secret token that identifies or authorizes a client making API requests. It lets an API restrict access without requiring another system to complete a Django login form. section 11.2.5
A practical API-key request flow looks like this:
- Store the accepted key in Django settings, such as NINJA_API_KEY. section 11.2.5
- Require the key through an HTTP header, such as X-API-KEY. section 11.2.5 section 11.5
- Compare the incoming value with the configured key and authenticate only when they match. section 11.2.5
- Attach the authentication handler globally, to a router, or to selected endpoint functions. section 11.2.5 section 11.5
Listing 11.12 Creating an authentication handler based on a key
# RiffMates/api_auth.py
from django.conf import settings
from ninja.security import APIKeyHeader
class APIKey(APIKeyHeader):
param_name = "X-API-KEY" #1
def authenticate(self, request, key):
if key == settings.NINJA_API_KEY: #2
return key #3
api_key = APIKey() #4
The handler subclasses APIKeyHeader, names the X-API-KEY header, compares its value with settings.NINJA_API_KEY, and returns the key when authentication succeeds. section 11.2.5
Choosing the authentication style
Use Django authentication when the API serves a web-based interface that can follow a login redirect. Prefer an API key when another system, an SPA, or a data-consuming library calls the API without an authentication session. section 11.2.5 section 11.5












