The following sections describe a complete Gateway workflow that uses the Micetro REST API client and other related classes.
The source code for this workflow is assumed to be stored in the
workflows
folder in the custom workspace of the host where
Gateway is run. Gateway is distributed as
a Docker image. When starting the Docker container, you can use a bind mount to mount
the container's directory /bluecat_gateway
to a folder on the host
where the workflow code will reside. This folder is called the custom workspace.
Gateway workflows created by the user should be placed in a
folder named workflows
within the custom workspace.
The file structure of this example will look like this:
<custom workspace>/
workflows/
micetro_example/
__init__.py
base.py
hooks.py
routes.py
spec.json
Below are files in this example workflow.
base.py
To make it easier for workflow developers to build Gateway workflows in Python, Gateway uses Flask. Flask is a lightweight Python web framework for web applications. Gateway automatically creates the Flask application for you, so that you can associate views to routes.
Flask uses the concept of blueprints to simplify applications. Blueprints help you structure your Flask application by grouping its functionality into reusable components.
The base.py
file creates a Blueprint
object and
registers it on our example workflow application at a specified URL prefix or
subdomain. This lets you start defining views and routes. Any API requests to this
example workflow will begin with the URL prefix
"/micetro_example
".
from flask import Blueprint
bp = Blueprint("micetro_example", __name__, url_prefix="/micetro_example")
hooks.py
In the hooks.py
file, we declare routes to the application. At the
minimum, this file must contain a def initialize()
function to
handle the initialize event..
def initialize():
"""Handle the 'initialize' event."""
# Load the modules that add routes to the blueprint instance.
from . import routes
def attach(application):
"""Attach request handlers to the web application."""
from .base import bp
application.register_blueprint(bp)
spec.json
The spec.json
file declares the workflow's Gateway access permissions. In this example, we've defined a new
Gateway permission named micetro_example
.
When the Gateway container is started,
micetro_example
will appear in the
Permissions page of the Gateway UI
(as long as the workflow is located in the custom workspace). From there,
administrators can configure access to the new workflow for Gateway user groups.
{
"permissions": ["micetro_example"]
}
routes.py
The routes.py
file defines routes and endpoints for this workflow. A
route or endpoint associates a request (as specified by a URL and HTTP method) to
the code that handles them.
The routes.py
file in this example workflow illustrates how to
access the authenticated Micetro REST API client provided by Gateway to make an API call to a Micetro server. The route defined
below responds to a GET HTTP request from a user by using authenticated Micetro REST
API client (g.user.micetro_api.v2
) to make a GET
/users
Micetro API call to the Micetro server.
from bluecat.gateway.decorators import require_permission
from bluecat.util import no_cache
from flask import g
from .base import bp
@bp.route("/micetro_user", methods=["GET"])
@no_cache
@require_permission("micetro_example")
def api_get_user():
# Get the API client.
api = g.user.micetro_api.v2
data = api.http_get("/users")["result"]
return {"data": data}
Accessing user authentication details: While Gateway is
running, you can check the authentication status by sending a GET
/users
call to the Micetro API. If this call is successful (the HTTP
response status code is 200), a subsequent use of the def
api_get_user()
method will retrieve details about the currently
authenticated user. The returned JSON data will look something like this:
{
"data": {
"totalResults": 1,
"users": [
{
"authenticationType": "Internal",
"description": "Micetro system administrator account.",
"email": "",
"externalID": "",
"fullName": "System Administrator",
"groupRoles": [],
"groups": [],
"lastLogin": "2024-06-24 09:08:35",
"name": "administrator",
"password": "",
"ref": "users/0",
"roles": []
}
]
}
}
Alternative routes.py example with error handling
The MicetroV2ErrorResponse exception is raised by Gateway when an error response is received from the Micetro server when an API call is made to it. The example route “/create_dns_record” in the routes.py file below, shows how the error can be handled.
The “errors” attribute within the JSON response contains information about the error that occurred.
from bluecat.gateway.decorators import api_exc_handler, require_permission
from bluecat.gateway.errors import InternalServerError
from bluecat.util import no_cache
from flask import g, request
from bluecat_libraries.micetro.apiv2.exceptions import MicetroV2ErrorResponse
from .base import bp
@bp.route("/create_dns_record", methods=["POST"])
@no_cache
@api_exc_handler(default_message="Failed to create resource record.")
@require_permission("mictro_example")
def api_create_dns_record():
payload_record = request.get_json()
try:
response = g.user.micetro_api.v2.http_post("/dnsRecords", json=payload_record)
if response["result"].get("errors"):
raise InternalServerError(response["result"].get("errors"))
except MicetroV2ErrorResponse as e:
raise InternalServerError(e.message) from e
return response