liveBook · Manning

API key

As explained in Django in Action

An API key is a secret token used to identify or authorize a client making API requests.

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:

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

How Django in Action covers it

How deep it goes
Explains header-based validation and authentication scope, but does not develop broader key-management practices.
Examples
Demonstrates an APIKeyHeader subclass using X-API-KEY and settings.NINJA_API_KEY.
What it assumes
Assumes basic Django and API familiarity while contrasting API keys with an existing Django login system.
What you can do after
Operate/configure Django Ninja endpoints with a header-based API-key authentication handler.
How it connects
Connects API keys with Django authentication, HTTP headers, NinjaAPI, routers, and endpoint functions.

Also explained in

Compare how 13 books explain API key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.