Client class - BlueCat Python Library - 23.1

BlueCat Python Library Guide

Locale
English
Product name
BlueCat Python Library
Version
23.1

class bluecat_libraries.address_manager.apiv2.Client(url, *, verify=True)

Bases: bluecat_libraries.http_client.client.Client

A client for making HTTP calls to BAM REST v2 API.

There is a method for each HTTP verb - GET, POST, PUT, PATCH, and DELETE - as well as a generic method for a HTTP request: http_get, http_post, http_put, http_patch, http_delete, and http_request. The functionality of the client relies on the use of these methods.

The benefits of this client over a direct use of the requests Python library are:

  1. Available methods for performing login and logout, as well as determining the version of the BlueCat Address Manager.

  2. The client keeps track of the authentication token and automatically sends it with each request.

  3. The client keeps track of the base API URL, needing only the relative path to be specified when making a request.

  4. The client automatically parses the responses and returns Python data structures - dictionaries or strings - based on the response content type.

  5. The client detects error responses and raises a Python exception, which holds the fields that the BAM API replied with, e.g, code.

Overall, users of the client can write less code and keep track of less data when making requests to the BAM REST v2 API.

Nonetheless, the client allows for taking advantage of the full functionality of the BAM REST v2 API by exposing all available requests parameters in its methods. That way a user can, for example, specify filters and fields selection through URL query parameters.

You need to authenticate to the BAM REST v2 API when making calls. The client will use HTTP header Authorization as per the BAM documentation. You have to either perform a login via the client method (with a username and a password) or set the auth property to the full value for the header, including the authorization scheme.

Note:

The client does not specify a value for the Accept header by default. This results in the Content-Type of the response to be determined by the defaults of BAM.

Example:

from bluecat_libraries.address_manager.apiv2 import Client, MediaType
import csv

# Retrieve the configurations. Request the data as per BAM's default content type.
with Client(<bam_host_url>) as client:
    client.login(<username>, <password>)
    response = client.http_get("/configurations")
    configurations = response["data"]
    for configuration in configurations:
        print(f'{configuration["id"]}: {configuration["name"]}')
    client.logout()

# Retrieve the configurations. Request that the response is in 'JSON' format.
# The result should contain only fields 'id' and 'name'.
with Client(<bam_host_url>) as client:
    client.login(<username>, <password>)
    response = client.http_get(
        "/configurations",
        params={"fields": "id,name"},
        headers={"Accept": MediaType.JSON},
    )
    configurations = response["data"]
    for configuration in configurations:
        print(f'{configuration["id"]}: {configuration["name"]}')
    client.logout()

# Retrieve configurations. Request that the response is in 'CSV' format.
# The result should contain only the first 10, ordered alphabetically by name.
with Client(<bam_host_url>) as client:
    client.login(<username>, <password>)
    configurations_csv = client.http_get(
        "/configurations",
        params={"orderBy": "asc(name)", "limit": "10"},
        headers={"Accept": MediaType.CSV},
    )
    configurations = list(csv.reader(configurations_csv.splitlines()))
    for configuration in configurations:
        # NOTE: The 'id' is the first value in a row, the 'name' is the third one.
        print(f"{configuration[0]}: {configuration[2]}")
    client.logout()

New in version 23.1.0.

property auth

The value that the client is configured to use for header Authorization when making requests to BAM REST v2 API.

Return type: str | None

property bam_url

A URL to the Address Manager the client is created for.

This is not the verbatim value given during initialization. It contains only the scheme, host, and (if specified) port, which will be used by the client.

Return type: str

property bam_version

The version of the BlueCat Address Manager the client is connected to.

Note:

The client has to be authenticated before the version can be determined.

Return type: Version

Returns: Version of BlueCat Address Manager.

http_delete(url, params=None, data=None, json=None, expected_status_codes=None, **kwargs)

Perform an HTTP DELETE request based on the provided parameters. See method http_request for details.

Return type: Union[dict, str]

http_get(url='', params=None, expected_status_codes=None, **kwargs)

Perform an HTTP GET request based on the provided parameters. See method http_request for details.

If expected_status_codes is not specified, it defaults to (200, ). 200 is the HTTP status code for successful response OK.

Note:

From BAM v9.5.0, we can use the GET request to filter data without url in the prefix.

Return type: Union[dict, str]

http_patch(url, params=None, data=None, json=None, expected_status_codes=None, **kwargs)

Perform an HTTP PATCH request based on the provided parameters. See method http_request for details.

Return type: Union[dict, str]

http_post(url, params=None, data=None, json=None, expected_status_codes=None, **kwargs)

Perform an HTTP POST request based on the provided parameters. See method http_request for details.

Return type: Union[dict, str]

http_put(url, params=None, data=None, json=None, expected_status_codes=None, **kwargs)

Perform an HTTP PUT request based on the provided parameters. See method http_request for details.

Return type: Union[dict, str]

http_request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None, expected_status_codes=None)

Perform an HTTP request to the Address Manager using the provided parameters.

The call will be made through the instance of requests.Session that the client maintains. The parameters have the same behaviour as their namesakes in the requests library. The only exception is url, whose value should be relative to the Address Manager URL, e.g., "/configurations".

Parameters Description
method (str)

HTTP method to be used, e.g., GET, POST, PUT, PATCH, DELETE.

url (str)

A URL, relative to the API root to be used for the request, e.g., /configurations. It must start with a forward slash.

params (Union[dict, list[tuple], bytes, NoneType], optional)

Query parameters to be passed in the request.

data (Union[dict, list[tuple], bytes, IO, NoneType], optional)

Value to send in the body of the request. It can be a dictionary, list of tuples, bytes, or file-like object.

headers (dict, optional)

HTTP headers to send with the request.

cookies (dict, optional)

Cookies to send with the request.

files (dict[str, IO], optional)

File-like objects for multipart encoding upload, e.g. {"filename": file_like_object}

auth (Union[tuple, Callable, NoneType], optional)

Object to handle HTTP Authentication.

timeout (Union[float, tuple, NoneType], optional)

How long to wait to receive data before giving up. If given as a tuple, it is used as (connect, read) timeouts.

allow_redirects (bool, optional)

Whether to allow redirects. Defaults to True.

proxies (dict, optional)

Mapping of protocol or protocol and hostname to a URL of a proxy to be used.

hooks (dict, optional)

Hooks to be called upon events.

stream (bool, optional)

Whether to immediately read the response content. Defaults to False.

verify (Union[bool, str, NoneType], optional)

Whether to verify the server’s TLS certificate. If a string is passed, it is treated as a path to a CA bundle to be used. Defaults to True.

cert (Union[str, tuple[str, str], NoneType], optional)

Path to a SSL client certificate file (.pem). If the certificate has a key, it can be provides as the second item in a tuple, with the first item being the path to the certificate file.

json (Any, optional)

Object to be sent as JSON in the body of the request.

expected_status_codes (Iterable[int], optional)

HTTP status codes that are acceptable as a status code of the HTTP response. If the received code does not match the passed values, an UnexpectedResponse is raised. If left empty, the status code validation is not performed.

Return type: Union[dict, str]

Returns: The data the API responded with. The client will process the response based on the stated content type and return either the JSON formatted data parsed into a Python object (e.g., a dict) or the verbatim body text.

Example:

from bluecat_libraries.address_manager.apiv2 import Client

# Retrieve the configurations. Request the data as per BAM's default content type.
with Client(<bam_host_url>) as client:
    client.login(<username>, <password>)
    response = client.http_request("GET", "/configurations")
    configurations = response["data"]
    for configuration in configurations:
        print(f'{configuration["id"]}: {configuration["name"]}')
    client.logout()

property is_authenticated

Whether the authentication necessary to communicate with the BlueCat Address Manager REST v2 API is set.

Return type: bool

login(username, password)

Log user into BAM and store authentication token for later use by subsequent calls.

Parameters Description
username (str)

BAM username.

password (str)

BAM password.

Return type: dict

Returns: The session information returned by BAM API v2 basic authentication token.

logout()

Log user out from BAM and clear any stored authentication token.

Return type: dict

Returns: The logged-out session information is returned by BAM API v2.