Building workflows that work with both REST v1 and REST v2 - Platform - BlueCat Gateway - 23.1

Gateway Administration Guide

Locale
English
Product name
BlueCat Gateway
Version
23.1

Under some circumstances, you might need to modify a workflow so that it works with both the Address Manager REST v1 API client and the Address Manager REST v2 API client. Only one of the Address Manager REST v2 API or the REST v1 API can be available within a single Gateway instance.

To do so, whenever your script attempts to use a REST API feature, first test whether the v1 or v2 client is available, then use the needed API call from the appropriate client. You can test whether the client is available with the property g.user.bam_api.v2.

  • If the REST v2 client is available, g.user.bam_api.v2 stores the Gateway REST v2 client instance.

    If the REST v2 client is not available, g.user.bam_api.v2 stores None. You should use the REST v1 client.

Tip: For a table of equivalent Address Manager REST v2 API endpoints for Address Manager Legacy v1 API endpoints, see v1 REST API to RESTful v2 API migration guide

The following script illustrates this technique.

from bluecat import route
from bluecat.gateway.decorators import api_exc_handler, require_user
from bluecat_libraries.address_manager.constants import ObjectType  # for REST v1 API values
from bluecat_libraries.address_manager.apiv2 import MediaType
from flask import g, jsonify
from main_app import app

def get_all_ipv4_blocks_v1(client: bluecat_libraries.address_manager.api.Client):
    results: list[dict] = []
    for config in client.get_entities(0, ObjectType.CONFIGURATION, 0, 1000):
        config_id = config["id"]

        # Blocks can contain other blocks. Thus, keep a list of parents to explore.
        parents_to_explore = [config_id]
        while parents_to_explore:
            parent_id = parents_to_explore.pop(0)
            blocks = client.get_entities(parent_id, ObjectType.IP4_BLOCK, 0, 1000)
            if not blocks:
                continue
            for block in blocks:
                parents_to_explore.append(block["id"])
                results.append({"id": block["id"], "range": block["properties"]["CIDR"]})
    return results

def get_all_ipv4_blocks_v2(client: bluecat_libraries.address_manager.apiv2.Client):
    data = client.http_get(
        "/blocks",
        params={
            "fields": "id, range",
            "filter": "type:eq('IPv4Block')",
        },
        headers={"Accept": MediaType.JSON},
    )
    return data["data"]
  
@route(app, "/example/ipv4_blocks", methods=["GET"])
@api_exc_handler
@require_user
def get_all_ipv4_blocks():
    if g.user.bam_api.v2:
        data = get_all_ipv4_blocks_v2(g.user.bam_api.v2)
    else:
        data = get_all_ipv4_blocks_v1(g.user.bam_api.v1)
    return data