Client class - BlueCat Python Library - 24.3.2

BlueCat Python Library Guide

ft:locale
en-US
Product name
BlueCat Python Library
Version
24.3.2

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

Bases: bluecat_libraries.http_client.client.Client

A client for making HTTP calls to Micetro REST 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 authentication.

  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 Micetro 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 Micetro REST API.

Nonetheless, the client allows for taking advantage of the full functionality of the Micetro REST 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 Micetro REST API via the client method (with a username
  • and a password) when making calls. The client will use HTTP header Authorization as per the Micetro documentation.

    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 Micetro.

    Example:

    from bluecat_libraries.micetro.apiv2 import Client, MediaType
    
    # Retrieve the users. Request the data as per Micetro's default content type.
    with Client(<micetro_url>) as client:
        client.authenticate(<username>, <password>)
        response = client.http_get("/users")
        users = response["result"]["users"]
        for user in users:
            print(f'{user["ref"]}: {user["name"]}')
    
    # Retrieve the users. Request that the response is in 'XML' format.
    with Client(<micetro_url>) as client:
        client.authenticate(<username>, <password>)
        response = client.http_get(
            "/users",
            headers={"Accept": MediaType.XML},
        )
        print(response)

    New in version 24.3.0.

property auth

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

Return type: str

authenticate(username, password, refresh_token=False)

Logs into Micetro using encoded credentials.

Creates a base64-encoded token from the provided username and password, verifies it with Micetro to ensure the credentials are valid, and stores the token for use in subsequent API calls.

When the client is already authenticated, this function behaves as follows:
    • If refresh_token is False, it raises a ClientError('Client is already authenticated.').

    • If refresh_token is True, it returns a newly generated token.

Parameters Description
username (str)

The username for the Micetro account.

password (str)

The password associated with the username.

refresh_token (bool, optional)

Retrieve a new token even if logged in.

Return type: str

Returns: A string that contains the authentication token.

Example:

from bluecat_libraries.micetro.apiv2 import Client

with Client(<micetro_url>) as client:
    client.authenticate(<micetro_username>, <micetro_password>)

New in version 24.3.0.

clear_token()

Clear token from client and session header

Return type: None

staticmethod generate_token(username, password)

Generate a token following the Basic Authentication standard.

Parameters Description
username

The username for the Micetro account.

password

The password associated with the username.

Return type: str

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.

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 Micetro 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 Micetro URL, e.g., "/users".

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., /users. 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 provided 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.micetro.apiv2 import Client

# Retrieve the users. Request the data as per Micetro's default content type.
with Client(<micetro_host_url>) as client:
    client.login(<username>, <password>)
    response = client.http_request("GET", "/users")
    users = response["result"]["users"]
    for user in users:
        print(f'{user["ref"]}: {user["name"]}')

property micetro_url

A URL to the Micetro server 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 micetro_version

The version of Micetro the client is connected to.

Note:

The client does not have to be authenticated to get version.

Return type: Version