Debian Codegraph @

docs/topics/browsable-api.md

raw
1 # The Browsable API
2
3 > It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
4 >
5 > — [Alfred North Whitehead][cite], An Introduction to Mathematics (1911)
6
7
8 API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`.
9
10 ## URLs
11
12 If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose.
13
14 ## Formats
15
16 By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
17
18 ## Authentication
19
20 To quickly add authentication to the browesable api, add a routes named `"login"` and `"logout"` under the namespace `"rest_framework"`. DRF provides default routes for this which you can add to your urlconf:
21
22 ```python
23 from django.urls import include, path
24
25 urlpatterns = [
26 # ...
27 path("api-auth/", include("rest_framework.urls", namespace="rest_framework"))
28 ]
29 ```
30
31
32 ## Form rendering
33
34 In order to render the HTML forms, the browsable API needs to know which fields each form should contain, so it asks the view for a serializer once per form. Each of those calls is made with the request method overridden to match the form being rendered, rather than the method that was actually used for the request.
35
36 This means that during a `GET` request the view may be called again with `self.request.method` set to `POST`, `PUT`, `PATCH`, `DELETE` or `OPTIONS`. Any code that branches on the request method will observe the overridden value. Two common cases are a `get_serializer_class()` implementation that returns a different serializer for read and write operations, and permission classes, which are checked for each method before its form is rendered. This is expected behavior, and only affects rendering of the browsable API.
37
38 ## Customizing
39
40 The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel.
41
42 To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
43
44 **templates/rest_framework/api.html**
45
46 {% extends "rest_framework/base.html" %}
47
48 ... # Override blocks with required customizations
49
50 ### Overriding the default theme
51
52 To replace the default theme, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme.
53
54 {% block bootstrap_theme %}
55 <link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
56 {% endblock %}
57
58 Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
59
60 You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
61
62 Full example:
63
64 {% extends "rest_framework/base.html" %}
65
66 {% block bootstrap_theme %}
67 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/flatly/bootstrap.min.css" type="text/css">
68 {% endblock %}
69
70 {% block bootstrap_navbar_variant %}{% endblock %}
71
72 For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the `style` block.
73
74 ---
75
76 ![Cerulean theme][cerulean]
77
78 *Screenshot of the bootswatch 'Cerulean' theme*
79
80 ---
81
82 ![Slate theme][slate]
83
84 *Screenshot of the bootswatch 'Slate' theme*
85
86 ---
87
88 ### Third party packages for customization
89
90 You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API:
91
92 * [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
93 * [drf-redesign][drf-redesign] - A package for customizing the API using Bootstrap 5. Modern and sleek design, it comes with the support for dark mode.
94 * [drf-material][drf-material] - Material design for Django REST Framework.
95
96 ---
97
98 ![API Root][drf-rw-api-root]
99
100 ![List View][drf-rw-list-view]
101
102 ![Detail View][drf-rw-detail-view]
103
104 *Screenshots of the drf-restwind*
105
106 ---
107
108 ---
109
110 ![API Root][drf-r-api-root]
111
112 ![List View][drf-r-list-view]
113
114 ![Detail View][drf-r-detail-view]
115
116 *Screenshot of the drf-redesign*
117
118 ---
119
120 ![API Root][drf-m-api-root]
121
122 ![List View][drf-m-api-root]
123
124 ![Detail View][drf-m-api-root]
125
126 *Screenshot of the drf-material*
127
128 ---
129
130 ### Blocks
131
132 All of the blocks available in the browsable API base template that can be used in your `api.html`.
133
134 * `body` - The entire html `<body>`.
135 * `bodyclass` - Class attribute for the `<body>` tag, empty by default.
136 * `bootstrap_theme` - CSS for the Bootstrap theme.
137 * `bootstrap_navbar_variant` - CSS class for the navbar.
138 * `branding` - Branding section of the navbar, see [Bootstrap components][bcomponentsnav].
139 * `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
140 * `script` - JavaScript files for the page.
141 * `style` - CSS stylesheets for the page.
142 * `title` - Title of the page.
143 * `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use `{{ block.super }}` to preserve the authentication links.
144
145 #### Components
146
147 All of the standard [Bootstrap components][bcomponents] are available.
148
149 #### Tooltips
150
151 The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content will display a tooltip on hover events.
152
153 ### Login Template
154
155 To add branding and customize the look-and-feel of the login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`. The template should extend from `rest_framework/login_base.html`.
156
157 You can add your site name or branding by including the branding block:
158
159 {% extends "rest_framework/login_base.html" %}
160
161 {% block branding %}
162 <h3 style="margin: 0 0 20px;">My Site Name</h3>
163 {% endblock %}
164
165 You can also customize the style by adding the `bootstrap_theme` or `style` block similar to `api.html`.
166
167 ### Advanced Customization
168
169 #### Context
170
171 The context that's available to the template:
172
173 * `allowed_methods` : A list of methods allowed by the resource
174 * `api_settings` : The API settings
175 * `available_formats` : A list of formats allowed by the resource
176 * `breadcrumblist` : The list of links following the chain of nested resources
177 * `content` : The content of the API response
178 * `description` : The description of the resource, generated from its docstring
179 * `name` : The name of the resource
180 * `post_form` : A form instance for use by the POST form (if allowed)
181 * `put_form` : A form instance for use by the PUT form (if allowed)
182 * `display_edit_forms` : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed
183 * `request` : The request object
184 * `response` : The response object
185 * `version` : The version of Django REST Framework
186 * `view` : The view handling the request
187 * `FORMAT_PARAM` : The view can accept a format override
188 * `METHOD_PARAM` : The view can accept a method override
189
190 You can override the `BrowsableAPIRenderer.get_context()` method to customize the context that gets passed to the template.
191
192 #### Not using base.html
193
194 For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
195
196 #### Handling `ChoiceField` with large numbers of items.
197
198 When a relationship or `ChoiceField` has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.
199
200 The simplest option in this case is to replace the select input with a standard text input. For example:
201
202 author = serializers.HyperlinkedRelatedField(
203 queryset=User.objects.all(),
204 style={'base_template': 'input.html'}
205 )
206
207 #### Autocomplete
208
209 An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.
210
211 There are [a variety of packages for autocomplete widgets][autocomplete-packages], such as [django-autocomplete-light][django-autocomplete-light], that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the `widget` keyword argument since it now uses templated HTML generation.
212
213 ---
214
215 [cite]: https://en.wikiquote.org/wiki/Alfred_North_Whitehead
216 [drfreverse]: ../api-guide/reverse.md
217 [ffjsonview]: https://addons.mozilla.org/en-US/firefox/addon/jsonview/
218 [chromejsonview]: https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc
219 [bootstrap]: https://getbootstrap.com/
220 [cerulean]: ../img/cerulean.png
221 [slate]: ../img/slate.png
222 [bswatch]: https://bootswatch.com/
223 [bcomponents]: https://getbootstrap.com/2.3.2/components.html
224 [bcomponentsnav]: https://getbootstrap.com/2.3.2/components.html#navbar
225 [autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
226 [django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
227 [drf-restwind]: https://github.com/youzarsiph/drf-restwind
228 [drf-rw-api-root]: ../img/drf-rw-api-root.png
229 [drf-rw-list-view]: ../img/drf-rw-list-view.png
230 [drf-rw-detail-view]: ../img/drf-rw-detail-view.png
231 [drf-redesign]: https://github.com/youzarsiph/drf-redesign
232 [drf-r-api-root]: ../img/drf-r-api-root.png
233 [drf-r-list-view]: ../img/drf-r-list-view.png
234 [drf-r-detail-view]: ../img/drf-r-detail-view.png
235 [drf-material]: https://github.com/youzarsiph/drf-material
236 [drf-m-api-root]: ../img/drf-m-api-root.png
237 [drf-m-list-view]: ../img/drf-m-list-view.png
238 [drf-m-detail-view]: ../img/drf-m-detail-view.png