I was wondering if it was possible to add custom auth headers for each "Try It Out" section of the docs produced by django-rest-swagger? I have setup custom token authentication for my REST API and just need a custom header specified for each request produced by the "Try it out!" button.
1 Answers
Okay so I have finally solved my own issue. Basically, I ended up overriding the default index.html with my custom one (added it to my own templates
directory as rest_framework_swagger/index.html
):
{% extends "rest_framework_swagger/base.html" %}
{% block extra_nav %}
<input type="text" id="auth_token" placeholder="Auth Token" />
<input class="submit" type="submit" value="Submit" data-sw-translate="">
{% endblock %}
{% block extra_scripts %}
<script>
var element = document.querySelector(("#api_selector"));
element.addEventListener("submit", function(event) {
event.preventDefault();
var token = $("#auth_token").val();
window.swaggerUi.api.clientAuthorizations.add("Authorization", new window.SwaggerClient.ApiKeyAuthorization("Authorization", token, "header"));
alert("authorization added: " + token);
});
</script>
{% endblock %}
Essentially, I added an input box (see extra_nav
block) to the navbar where the user would simply place their custom header value (in my case it was the authentication header). Once the user clicks on the submit button, my custom script (see extra_scripts
) is executed where it prevents form submission (django-rest-swagger placed my input box in a form with the id of api_selector
and then adds the token value to the request headers. From here, ANY "Try It Out" button will now have the extra custom request header.
For more information on overriding the default django-rest-swagger ui: http://django-rest-swagger.readthedocs.io/en/latest/customization/
For more information about overriding templates: Override templates of external app in Django

- 1
- 1

- 3,210
- 6
- 27
- 37
-
1Just to make it a bit clearer on where those templates should be stored. Suppose your initial app is called `core`. Then you should add template to this location `core/templates/rest_framework_swagger/index.html`. Afterwards make newly added template visible by modifying `core/settings/base.py` like that: `TEMPLATES = [{'DIRS': [os.path.join(BASE_DIR, 'templates')]}]` – Žilvinas Rudžionis May 22 '17 at 10:09