Skip to content
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
a10326d
Fix hierarchy of the serializers page
browniebroke Mar 3, 2026
b7b8e8d
Disable toc.integrate feature
browniebroke Mar 3, 2026
ef5a9b5
Fix hierarchy of the authentication page
browniebroke Mar 3, 2026
966768e
Fix hierarchy of the content negotiation page
browniebroke Mar 3, 2026
7d15d3d
Fix hierarchy of the exceptions page
browniebroke Mar 3, 2026
62190a5
Fix hierarchy of the serializer fields page
browniebroke Mar 3, 2026
2b20f14
Fix hierarchy of the requests page
browniebroke Mar 3, 2026
0449f25
Fix hierarchy of the filtering page
browniebroke Mar 3, 2026
3b114b2
Fix hierarchy of the generic views page
browniebroke Mar 3, 2026
dcae808
Move level 2 header lower
browniebroke Mar 3, 2026
465c785
Turn field arguments into bullet points
browniebroke Mar 3, 2026
66b699d
Fix hierarchy of the metadata page
browniebroke Mar 3, 2026
582492c
Fix hierarchy of the pagination page
browniebroke Mar 3, 2026
103d37b
Fix hierarchy of the parsers page
browniebroke Mar 3, 2026
b1ffd06
Fix hierarchy of the permissions page
browniebroke Mar 3, 2026
a7bf595
Fix hierarchy of the relations page
browniebroke Mar 3, 2026
f96e2b7
Fix hierarchy of the renderers page
browniebroke Mar 3, 2026
59ff883
Fix hierarchy of the responses page
browniebroke Mar 3, 2026
3ffdbc3
Fix hierarchy of the routers page
browniebroke Mar 3, 2026
08e29be
Fix hierarchy of the settings page
browniebroke Mar 3, 2026
ca52472
Fix hierarchy of the testing page
browniebroke Mar 3, 2026
885d51e
Fix hierarchy of the throttling page
browniebroke Mar 3, 2026
72fa3dc
Fix hierarchy of the validators page
browniebroke Mar 3, 2026
053fc1e
Fix hierarchy of the versioning page
browniebroke Mar 3, 2026
a990f8c
Fix hierarchy of the views page
browniebroke Mar 3, 2026
d194d26
Fix hierarchy of the viewsets page
browniebroke Mar 3, 2026
9b6acc4
Fix hierarchy of the community pages
browniebroke Mar 3, 2026
0d56566
Apply suggestion from @Copilot
browniebroke Mar 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 29 additions & 31 deletions docs/api-guide/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ source:
- authentication.py
---

# Authentication

> Auth needs to be pluggable.
>
> — Jacob Kaplan-Moss, ["REST worst practices"][cite]
Expand Down Expand Up @@ -104,9 +102,9 @@ If you are deploying to Apache, and using any non-session based authentication,

---

# API Reference
## API Reference

## BasicAuthentication
### BasicAuthentication

This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.

Expand All @@ -122,7 +120,7 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
!!! note
If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.

## TokenAuthentication
### TokenAuthentication

!!! note
The token authentication provided by Django REST framework is a fairly simple implementation.
Expand Down Expand Up @@ -171,9 +169,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
!!! note
If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.

### Generating Tokens
#### Generating Tokens

#### By using signals
##### By using signals

If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.

Expand All @@ -197,7 +195,7 @@ If you've already created some users, you can generate tokens for all existing u
for user in User.objects.all():
Token.objects.get_or_create(user=user)

#### By exposing an api endpoint
##### By exposing an api endpoint

When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:

Expand Down Expand Up @@ -246,7 +244,7 @@ And in your `urls.py`:
]


#### With Django admin
##### With Django admin

It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.

Expand All @@ -257,7 +255,7 @@ It is also possible to create Tokens manually through the admin interface. In ca
TokenAdmin.raw_id_fields = ['user']


#### Using Django manage.py command
##### Using Django manage.py command

Since version 3.6.4 it's possible to generate a user token using the following command:

Expand All @@ -272,7 +270,7 @@ In case you want to regenerate the token (for example if it has been compromised
./manage.py drf_create_token -r <username>


## SessionAuthentication
### SessionAuthentication

This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.

Expand All @@ -291,7 +289,7 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.


## RemoteUserAuthentication
### RemoteUserAuthentication

This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
environment variable.
Expand All @@ -312,7 +310,7 @@ Consult your web server's documentation for information about configuring an aut
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)


# Custom authentication
## Custom authentication

To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.

Expand All @@ -330,7 +328,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
!!! note
When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.

## Example
### Example

The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.

Expand All @@ -353,19 +351,19 @@ The following example will authenticate any incoming request as the user given b

---

# Third party packages
## Third party packages

The following third-party packages are also available.

## django-rest-knox
### django-rest-knox

[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).

## Django OAuth Toolkit
### Django OAuth Toolkit

The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.

### Installation & configuration
#### Installation & configuration

Install using `pip`.

Expand All @@ -386,42 +384,42 @@ Add the package to your `INSTALLED_APPS` and modify your REST framework settings

For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation.

## Django REST framework OAuth
### Django REST framework OAuth

The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.

This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.

### Installation & configuration
#### Installation & configuration

Install the package using `pip`.

pip install djangorestframework-oauth

For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions].

## JSON Web Token Authentication
### JSON Web Token Authentication

JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides some features as well as a pluggable token blacklist app.

## Hawk HTTP Authentication
### Hawk HTTP Authentication

The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]).

## HTTP Signature Authentication
### HTTP Signature Authentication

HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].

## Djoser
### Djoser

[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.

## DRF Auth Kit
### DRF Auth Kit

[DRF Auth Kit][drf-auth-kit] library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages.


## django-rest-auth / dj-rest-auth
### django-rest-auth / dj-rest-auth

This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.

Expand All @@ -431,25 +429,25 @@ There are currently two forks of this project.
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
* [Dj-rest-auth][dj-rest-auth] is a newer fork of the project.

## drf-social-oauth2
### drf-social-oauth2

[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.

## drfpasswordless
### drfpasswordless

[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.

## django-rest-authemail
### django-rest-authemail

[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.

## Django-Rest-Durin
### Django-Rest-Durin

[Django-Rest-Durin][django-rest-durin] is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.

More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).

## django-pyoidc
### django-pyoidc

[django_pyoidc][django-pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.

Expand Down
8 changes: 3 additions & 5 deletions docs/api-guide/content-negotiation.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ source:
- negotiation.py
---

# Content negotiation

> HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.
>
> &mdash; [RFC 2616][cite], Fielding et al.
Expand Down Expand Up @@ -40,7 +38,7 @@ For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]

This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.

# Custom content negotiation
## Custom content negotiation

It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`.

Expand All @@ -50,7 +48,7 @@ The `select_parser()` method should return one of the parser instances from the

The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception.

## Example
### Example

The following is a custom content negotiation class which ignores the client
request when selecting the appropriate parser or renderer.
Expand All @@ -70,7 +68,7 @@ request when selecting the appropriate parser or renderer.
"""
return (renderers[0], renderers[0].media_type)

## Setting the content negotiation
### Setting the content negotiation

The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class.

Expand Down
34 changes: 17 additions & 17 deletions docs/api-guide/exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ Note that the exception handler will only be called for responses generated by r

---

# API Reference
## API Reference

## APIException
### APIException

**Signature:** `APIException()`

Expand Down Expand Up @@ -143,79 +143,79 @@ dictionary of items:
>>> print(exc.get_full_details())
{"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}}

## ParseError
### ParseError

**Signature:** `ParseError(detail=None, code=None)`

Raised if the request contains malformed data when accessing `request.data`.

By default this exception results in a response with the HTTP status code "400 Bad Request".

## AuthenticationFailed
### AuthenticationFailed

**Signature:** `AuthenticationFailed(detail=None, code=None)`

Raised when an incoming request includes incorrect authentication.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.

## NotAuthenticated
### NotAuthenticated

**Signature:** `NotAuthenticated(detail=None, code=None)`

Raised when an unauthenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.

## PermissionDenied
### PermissionDenied

**Signature:** `PermissionDenied(detail=None, code=None)`

Raised when an authenticated request fails the permission checks.

By default this exception results in a response with the HTTP status code "403 Forbidden".

## NotFound
### NotFound

**Signature:** `NotFound(detail=None, code=None)`

Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception.

By default this exception results in a response with the HTTP status code "404 Not Found".

## MethodNotAllowed
### MethodNotAllowed

**Signature:** `MethodNotAllowed(method, detail=None, code=None)`

Raised when an incoming request occurs that does not map to a handler method on the view.

By default this exception results in a response with the HTTP status code "405 Method Not Allowed".

## NotAcceptable
### NotAcceptable

**Signature:** `NotAcceptable(detail=None, code=None)`

Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers.

By default this exception results in a response with the HTTP status code "406 Not Acceptable".

## UnsupportedMediaType
### UnsupportedMediaType

**Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)`

Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`.

By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".

## Throttled
### Throttled

**Signature:** `Throttled(wait=None, detail=None, code=None)`

Raised when an incoming request fails the throttling checks.

By default this exception results in a response with the HTTP status code "429 Too Many Requests".

## ValidationError
### ValidationError

**Signature:** `ValidationError(detail=None, code=None)`

Expand All @@ -235,35 +235,35 @@ By default this exception results in a response with the HTTP status code "400 B

---

# Generic Error Views
## Generic Error Views

Django REST Framework provides two error views suitable for providing generic JSON `500` Server Error and
`400` Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an
API-only application.)

Use these as per [Django's Customizing error views documentation][django-custom-error-views].

## `rest_framework.exceptions.server_error`
### `rest_framework.exceptions.server_error`

Returns a response with status code `500` and `application/json` content type.

Set as `handler500`:

handler500 = 'rest_framework.exceptions.server_error'

## `rest_framework.exceptions.bad_request`
### `rest_framework.exceptions.bad_request`

Returns a response with status code `400` and `application/json` content type.

Set as `handler400`:

handler400 = 'rest_framework.exceptions.bad_request'

# Third party packages
## Third party packages

The following third-party packages are also available.

## DRF Standardized Errors
### DRF Standardized Errors

The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.

Expand Down
Loading