How to stop Django Rest Framework from leaking docstrings into OPTIONS responses
When you make an HTTP OPTIONS request against an endpoint in a Django Rest Framework app you might be surprised about what you’ll find in the response to that request.
In its default configuration Rest Framework returns a bunch of metadata that you might not want to return as part of the response. Here’s an example:
$ http OPTIONS localhost:8000/api/v1/test/
HTTP/1.0 200 OK Allow: POST, OPTIONS Content-Type: application/json Date: Tue, 02 Mar 2016 8:23:00 GMT Server: WSGIServer/0.2 CPython/3.5.1 Vary: Cookie
{"description":"This is the docstring of the view handling the request\nThis might contain information you don't want to leak out in an OPTIONS request.\n","name":"Test Endpoint","parses":["application/x-www-form-urlencoded","multipart/form-data","application/json"],"renders":["application/json"]}
As you can see, by default the response includes the full docstring for the view as part of the description
field. If that’s not what you want you can configure the metadata returned by Django Rest Framework through the metadata scheme mechanism.
Here’s a null metadata scheme that configures OPTIONS
responses to be empty:
fromrest_framework.metadataimportBaseMetadataclassNoMetaData(BaseMetadata):defdetermine_metadata(self,request,view):returnNone
To set that metadata class globally we can use the DEFAULT_METADATA_CLASS
setting in Rest Framework:
REST_FRAMEWORK={'DEFAULT_METADATA_CLASS':'yourapp.metadata.NoMetaData'}
When we make the same OPTIONS
request now we get the empty response we wanted:
$ http OPTIONS localhost:8000/api/v1/test/
HTTP/1.0 200 OK Allow: POST, OPTIONS Content-Type: application/json Date: Tue, 02 Mar 2016 8:42:00 GMT Server: WSGIServer/0.2 CPython/3.5.1 Vary: Cookie