Metadata

REST framework includes a configurable mechanism for determining how your API should respond to OPTIONS requests. This allows you to return API schema or other resource information.

There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP OPTIONS requests, so we provide an ad-hoc style that returns some useful information.

Here's an example response that demonstrates the information that is returned by default.

  1. REST_FRAMEWORK = {
  2. 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
  3. }

Or you can set the metadata class individually for a view:

The REST framework package only includes a single metadata class implementation, named . If you want to use an alternative style you'll need to implement a custom metadata class.

If you have specific requirements for creating schema endpoints that are accessed with regular GET requests, you might consider re-using the metadata API for doing so.

For example, the following additional route could be used on a viewset to provide a linkable schema endpoint.

  1. @action(methods=['GET'], detail=False)
  2. def schema(self, request):
  3. data = meta.determine_metadata(request, self)
  4. return Response(data)

There are a couple of reasons that you might choose to take this approach, including that responses are not cacheable.


Custom metadata classes

Useful things that you might want to do could include returning schema information, using a format such as , or returning debug information to admin users.

The following class could be used to limit the information that is returned to OPTIONS requests.

Then configure your settings to use this custom class:

  1. REST_FRAMEWORK = {
  2. 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata'
  3. }

Third party packages

The following third party packages provide additional metadata implementations.

drf-schema-adapter is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate as well as schema information readable by various libraries.