9browsable Api
9browsable Api
In the Terminal
Clone the repo. Your command should look something like this:
Basic customization
As part of this course you’ve had a chance to interact with the Django Rest
Framework GUI. It’s a great, intuitive tool, and it automatically changes the
fields it displays based on the permissions available to you at the time,
Most of the time, you won’t need to customize the DRF GUI at all, however
we’ll take a quick look at some of the things you can do.
DRF uses the Bootstrap CSS framework, although a slightly older version
than what we use for the rest of the project (v3.3.5). The concepts are
similar and the documentation is still available so you should be able to
figure out what tools and classes you have available to use.
To customise the look of the API page you’ll need to start by creating a
template, rest_framework/api.html, which extends from
rest_framework/base.html.
body: The entire html <body>. You usually don’t want to use this as it
replaces the entire body of the page.
bodyclass: Class attribute for the <body> tag, empty by default.
bootstrap_theme: CSS for the Bootstrap theme.
bootstrap_navbar_variant: CSS class for the navbar.
branding: Branding section of the navbar, see Bootstrap components.
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.
script: JavaScript files for the page.
style: CSS stylesheets for the page.
title: Title of the page.
userlinks: This is a list of links on the right of the header, by default
containing login/logout links. To add links instead of replacing, use {{
block.super }} to preserve the authentication links.
As well as overriding these blocks, the following context variables are also
passed to the template:
If you do want to customize the DRF GUI, most often it will be to show your
own branding. Let’s set up some Blango branding on our browsable API.
Try It Out
Let’s make some changes to the DRF template to set our own “Blango”
branding. Create a rest_framework directory inside the templates directory
for your project (that is, the templates directory of the blango project, not
inside the blog or blango_auth directories).
Open api.html
{% extends "rest_framework/base.html" %}
Next we will override the title of the page. This is the same logic that the
main api.html template uses, to show the name of the page and then the
name of the API. Add this under the extends template tag.
Then we’ll update the branding, which is displayed in the upper left corner
of the page, by overriding the branding block. We’ll set this to the Blango
REST API. Add this next:
{% block branding %}
<a href="/" class="navbar-brand">
Blango REST API
</a>
{% endblock %}
The final change we’ll make is a small style tweak: we’ll change the top
border of the page from red to blue. To do this we will add a <style>
element inside the style block, making sure to also include block.super so
we retain the original style rules too. Add this to the end of the api.html
file.
{% block style %}
{{ block.super }}
<style>
div .navbar {
border-top-color: #1E90FF;
}
</style>
{% endblock %}
Go ahead and load up a DRF page in your browser, you should see the
changes to the title, branding and border color.
View Blog
branding changes
That’s just a small sample of what can be changed, refer to the official DRF
browsable API documentation for more information.
Swagger UI
Swagger is a third-party tool that generates a browsable API from an
OpenAPI specification. This is an open standard, so many different APIs can
generate API documents in the correct format, and use Swagger to build the
UI. Different Python frameworks (like Flask) or even frameworks in other
languages are compatible with OpenAPI and Swagger. You might have even
used Swagger before, when working with other APIs. Because of its
ubiquity you might consider providing a Swagger UI that other developers
will be more familiar with than DRF’s built-in one.
DRF does have built-in support for generating a simple Swagger UI,
however it’s a bit too basic. With the addition of a third-party library we
can get a more full-featured one with only a few additions.
SWAGGER_SETTINGS = {
"SECURITY_DEFINITIONS": {
"Token": {"type": "apiKey", "name": "Authorization",
"in": "header"},
"Basic": {"type": "basic"},
}
}
DRF YASG implements two independent views: one that renders the
specification in JSON or YAML, and another that renders the Swagger UI.
Other clients can download the spec and build their own API
documentation from it. Or, users can use the Swagger UI as a browsable UI
to interact with our API.
schema_view = get_schema_view(
openapi.Info(
title="Blango API",
default_version="v1",
description="API for Blango Blog",
),
public=True,
)
Now we can map the URLs to the view – or rather we map them to different
functions on the schema_view generated class. First we need the re_path
function to use regular expressions in the URL pattern.
Then we create a URL for fetching the spec, which can be retrieved in JSON
or YAML format. We’re mapping the path swagger.json and swagger.yaml
to the without_ui() method of the class.
urlpatterns += [
# ...
re_path(
r"^swagger(?P<format>\.json|\.yaml)$",
schema_view.without_ui(cache_timeout=0),
name="schema-json",
),
# ...
]
Hitting this URL will show us JSON representing all the endpoints.
open api schema
Finally we can map a URL to the Swagger UI itself. This will map the path
api/v1/swagger/ to the schema view’s with_ui() method.
urlpatterns += [
# ...
path(
r"^swagger/$",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
),
# ...
]
Redoc UI
We could also pass in the string “redoc” to get a Redoc UI, which is a
different API browsing/documentation tool.
We’re all done, here’s what the Swagger UI looks like in the browser.
swagger ui
Now you’ll get Swagger UI up and running on your Blango project and then
test it out.
Try It Out
Try It Out
Start by installing drf-yasg with pip in the terminal:
Open settings.py
SWAGGER_SETTINGS = {
"SECURITY_DEFINITIONS": {
"Token": {"type": "apiKey", "name": "Authorization",
"in": "header"},
"Basic": {"type": "basic"},
}
}
Now we need to map URLs to the views that DRF YASG provides. Open the
blog/api/urls.py file, and add/update these imports at the start of the file:
Open api/urls.py
url=f"https://{os.environ.get('CODIO_HOSTNAME')}-8000.cod
io.io/api/v1/",
public=True,
)
Now we can map URLs to the methods on the schema_view class. Add the
rules to list that is added on to the urlpatterns:
urlpatterns += [
path("auth/", include("rest_framework.urls")),
path("token-auth/", views.obtain_auth_token),
re_path(
r"^swagger(?P<format>\.json|\.yaml)$",
schema_view.without_ui(cache_timeout=0),
name="schema-json",
),
path(
"swagger/",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
),
]
View Blog
swagger authorization
The UI also supports session authentication though, just like the DRF
Browsable UI.
The Swagger UI is quite intuitive. Click a path to expand it, and see the
schema details. Click Try it out to show fields for entering the request data,
then click Execute to make the request. The next image shows a Post list
response.
Pushing to GitHub
Before continuing, you must push your work to GitHub. In the terminal:
git add .
git commit -m "Finish browsable API"
Push to GitHub:
git push