Skip to content

Nexus Dashboard

wingpy.cisco.nexusdashboard.CiscoNexusDashboard

CiscoNexusDashboard(
    *,
    base_url: str | None = None,
    username: str | None = None,
    authdomain: str | None = None,
    apikey: str | None = None,
    password: str | None = None,
    verify: SSLContext | bool = True,
    timeout: int = 10,
    retries: int = 3
)

Bases: RestApiBaseClass

Interact with the Cisco Nexus Dashboard API.

Parameters:

Name Type Description Default
base_url str | None

Base URL of the API including https://.

Overrides the environment variable WINGPY_NEXUS_DASHBOARD_BASE_URL.

None
username str | None

Username for API authentication.

Overrides the environment variable WINGPY_NEXUS_DASHBOARD_USERNAME.

None
authdomain str | None

Domain name for API authentication.

Overrides the environment variable WINGPY_NEXUS_DASHBOARD_USERNAME.

DefaultAuth
password str | None

Password for API authentication. Not supported together with apikey

Overrides the environment variable WINGPY_NEXUS_DASHBOARD_PASSWORD

None
apikey str | None

Key for API authentication. Not supported together with password

Overrides the environment variable WINGPY_NEXUS_DASHBOARD_APIKEY

None
verify bool | SSLContext

Boolean values will enable or disable the default SSL verification.

Use an ssl.SSLContext to specify custom Certificate Authority.

True
timeout int

Number of seconds to wait for HTTP responses before raising httpx.TimeoutException exception.

10
retries int

Number of failed HTTP attempts allowed before raising httpx.HTTPStatusError exception.

3

Examples:

from wingpy import CiscoNexusDashboard
nexusdashboard = CiscoNexusDashboard(
    base_url="https://nd.example.com/api/v1/infra/",
    username="example_username",
    password="example_password",
)
nexusdashboard.get("/systemResources/summary")
Source code in src/wingpy/cisco/nexusdashboard.py
def __init__(
    self,
    *,
    base_url: str | None = None,
    username: str | None = None,
    authdomain: str | None = None,
    apikey: str | None = None,
    password: str | None = None,
    verify: SSLContext | bool = True,
    timeout: int = 10,
    retries: int = 3,
):
    # Allow parameters to be passed directly or fallback to environment variables
    self.nexusdashboard_url = base_url or os.getenv(
        "WINGPY_NEXUS_DASHBOARD_BASE_URL"
    )
    """
    The base URL for the Cisco Nexus Dashboard API.

    If not provided, it will be read from the environment variable `WINGPY_NEXUS_DASHBOARD_BASE_URL`.
    """

    self.username = username or os.getenv("WINGPY_NEXUS_DASHBOARD_USERNAME")
    """
    The username for authentication.
    If not provided, it will be read from the environment variable `WINGPY_NEXUS_DASHBOARD_USERNAME`.
    """

    self.password = password or os.getenv("WINGPY_NEXUS_DASHBOARD_PASSWORD")
    """
    The password for authentication.
    If not provided, it will be read from the environment variable `WINGPY_NEXUS_DASHBOARD_PASSWORD`.
    Not supported with `apikey`.
    """

    self.apikey = apikey or os.getenv("WINGPY_NEXUS_DASHBOARD_APIKEY")
    """
    The API key used for authentication.
    If not provided, it will be read from the environment variable `WINGPY_NEXUS_DASHBOARD_APIKEY`.
    Not supported with `password`.
    """

    if self.password and self.apikey:
        raise ValueError("Password and API key not supported simultaneously.")

    self.authdomain = (
        authdomain
        or os.getenv("WINGPY_NEXUS_DASHBOARD_AUTHDOMAIN")
        or "DefaultAuth"
    )
    """
    The name of the authentication domain for authentication.
    If not provided, it will be read from the environment variable `WINGPY_NEXUS_DASHBOARD_AUTHDOMAIN`.

    """

    self.token = None
    """
    The authentication token for the Cisco Nexus Dashboard API.
    """

    if not self.nexusdashboard_url:
        raise ValueError(
            "Cisco Nexus Dashboard base_url must be provided either as argument or environment variable"
        )

    self.version: Version = Version("0.0")
    """
    The version of the Cisco Nexus Dashboard API.
    """

    super().__init__(
        base_url=self.nexusdashboard_url,
        auth_lifetime=1200,
        auth_refresh_percentage=0.9,
        verify=verify,
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        timeout=timeout,
        retries=retries,
    )

get

get(
    path: str,
    *,
    params: dict | None = None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None
) -> httpx.Response

Send an HTTP GET request to the specified path.

Parameters:

Name Type Description Default
path str

The API endpoint path to send the request to.

required
params dict | None

URL query parameters to include in the request. will be added as ?key=value pairs in the URL.

None
path_params dict | None

Replace placeholders like {siteId} in the URL path with actual values.

Will be combined with self.path_params before sending request.

None
headers dict | None

HTTP headers to be sent with the request.

Will be combined with self.headers before sending request.

None
timeout int | None

Override the standard timeout timer self.timeout for a single request.

None

Returns:

Type Description
Response

The httpx.Response object from the request.

Source code in src/wingpy/cisco/nexusdashboard.py
def get(
    self,
    path: str,
    *,
    params: dict | None = None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
) -> httpx.Response:
    """
    Send an HTTP `GET` request to the specified path.

    Parameters
    ----------
    path : str
        The API endpoint path to send the request to.

    params : dict | None, default=None
        URL query parameters to include in the request. will be added as `?key=value` pairs in the URL.

    path_params : dict | None, default=None
        Replace placeholders like `{siteId}` in the URL path with actual values.

        Will be combined with [self.path_params](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.path_params) before sending request.

    headers : dict | None, default=None
        HTTP headers to be sent with the request.

        Will be combined with [self.headers](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.headers) before sending request.

    timeout : int | None, default=None
        Override the standard timeout timer [self.timeout](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.timeout) for a single request.

    Returns
    -------
    httpx.Response
        The [`httpx.Response`](https://www.python-httpx.org/api/#response) object from the request.
    """

    response = self.request(
        "GET",
        path,
        data=None,
        params=params,
        path_params=path_params,
        headers=headers,
        timeout=timeout,
        is_auth_endpoint=False,
        auth=None,
    )
    return response

get_all

get_all(
    path: str,
    *,
    params: dict | None = None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
    page_size: int = 10000
) -> list

Retrieves all pages of data from a GET endpoint using maximum concurrency.

Parameters:

Name Type Description Default
path str

The API endpoint path to send the request to.

required
params dict | None

URL query parameters to include in the request. will be added as ?key=value pairs in the URL.

None
path_params dict | None

Replace placeholders like {objectId} in the URL path with actual values.

Will be combined with self.path_params before sending request.

None
headers dict | None

HTTP headers to be sent with the request.

Will be combined with self.headers before sending request.

None
timeout int | None

Override the standard timeout timer self.timeout for a single request.

None
page_size int

The number of items to retrieve per page.

500

Returns:

Type Description
list[dict]

A concatenated list of returned dictionaries from all pages.

Similar to the response key in the Cisco Nexus Dashboard API JSON responses.

Source code in src/wingpy/cisco/nexusdashboard.py
def get_all(
    self,
    path: str,
    *,
    params: dict | None = None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
    page_size: int = 10000,
) -> list:
    """
    Retrieves all pages of data from a `GET` endpoint using maximum concurrency.

    Parameters
    ----------
    path : str
        The API endpoint path to send the request to.

    params : dict | None, default=None
        URL query parameters to include in the request. will be added as `?key=value` pairs in the URL.

    path_params : dict | None, default=None
        Replace placeholders like `{objectId}` in the URL path with actual values.

        Will be combined with [self.path_params](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.path_params) before sending request.

    headers : dict | None, default=None
        HTTP headers to be sent with the request.

        Will be combined with [self.headers](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.headers) before sending request.

    timeout : int | None, default=None
        Override the standard timeout timer [self.timeout](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.timeout) for a single request.

    page_size : int, default=500
        The number of items to retrieve per page.

    Returns
    -------
    list[dict]
        A concatenated list of returned dictionaries from all pages.

        Similar to the `response` key in the Cisco Nexus Dashboard API JSON responses.
    """

    logger.debug(f"Retrieving all pages from {path}")

    first_page = self.get_page(
        path,
        params=params,
        path_params=path_params,
        offset=0,
        limit=page_size,
    )

    json_response_data = first_page.json()

    total = json_response_data.get("meta", {}).get("counts", {}).get("total")

    if not isinstance(total, int):
        error = UnexpectedPayloadError(
            "Integer not found in meta.counts.total for paginated endpoint",
            response=first_page,
        )
        log_exception(error)
        raise error

    result_key = None

    for key, value in json_response_data.items():
        if isinstance(value, list):
            logger.trace(f"Using list with key '{key}' for page content")
            result_key = key
            break

    if not result_key:
        error = UnexpectedPayloadError(
            "No lists for pagination found in payload",
            response=first_page,
        )
        log_exception(error)
        raise error

    result: list = json_response_data[result_key]

    total_count = int(json_response_data["meta"]["counts"]["total"])

    logger.debug(f"Paging with {range(page_size, total_count, page_size) = }")

    # Prepare the pages to be retrieved in parallel
    for offset in range(page_size, total_count, page_size):
        self.tasks.schedule(
            self.get_page,
            path,
            params=params,
            path_params=path_params,
            headers=headers,
            timeout=timeout,
            offset=offset,
            limit=page_size,
        )

    page_responses = self.tasks.run()

    for page_response in page_responses.values():
        print(len(page_response.json().get(result_key, [])))
        result += page_response.json().get(result_key, [])

    logger.debug(f"Received {len(result)} items from {path}")

    return result

post

post(
    path: str,
    *,
    data: str | dict | list | None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None
) -> httpx.Response

Send an HTTP POST request to the specified path.

Parameters:

Name Type Description Default
path str

The API endpoint path to send the request to.

required
data str | dict | list | None

Request payload as JSON string or Python list/dict object.

required
path_params dict | None

Replace placeholders like {siteId} in the URL path with actual values.

Will be combined with self.path_params before sending request.

None
headers dict | None

HTTP headers to be sent with the request.

Will be combined with self.headers before sending request.

None
timeout int | None

Override the standard timeout timer self.timeout for a single request.

None

Returns:

Type Description
Response

The httpx.Response object from the request.

Source code in src/wingpy/cisco/nexusdashboard.py
def post(
    self,
    path: str,
    *,
    data: str | dict | list | None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
) -> httpx.Response:
    """
    Send an HTTP `POST` request to the specified path.

    Parameters
    ----------
    path : str
        The API endpoint path to send the request to.

    data : str | dict | list | None
        Request payload as JSON string or Python list/dict object.

    path_params : dict | None, default=None
        Replace placeholders like `{siteId}` in the URL path with actual values.

        Will be combined with [self.path_params](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.path_params) before sending request.

    headers : dict | None, default=None
        HTTP headers to be sent with the request.

        Will be combined with [self.headers](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.headers) before sending request.

    timeout : int | None, default=None
        Override the standard timeout timer [self.timeout](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.timeout) for a single request.

    Returns
    -------
    httpx.Response
        The [`httpx.Response`](https://www.python-httpx.org/api/#response) object from the request.
    """

    response = self.request(
        "POST",
        path,
        data=data,
        params=None,
        path_params=path_params,
        headers=headers,
        timeout=timeout,
        is_auth_endpoint=False,
        auth=None,
    )

    return response

put

put(
    path: str,
    *,
    data: str | dict | list | None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None
) -> httpx.Response

Send an HTTP PUT request to the specified path.

Parameters:

Name Type Description Default
path str

The API endpoint path to send the request to.

required
data str | dict | list

Request payload as JSON string or Python list/dict object.

required
path_params dict | None

Replace placeholders like {siteId} in the URL path with actual values.

Will be combined with self.path_params before sending request.

None
headers dict | None

HTTP headers to be sent with the request.

Will be combined with self.headers before sending request.

None
timeout int | None

Override the standard timeout timer self.timeout for a single request.

None

Returns:

Type Description
Response

The httpx.Response object from the request.

Source code in src/wingpy/cisco/nexusdashboard.py
def put(
    self,
    path: str,
    *,
    data: str | dict | list | None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
) -> httpx.Response:
    """
    Send an HTTP `PUT` request to the specified path.

    Parameters
    ----------
    path : str
        The API endpoint path to send the request to.

    data : str | dict | list
        Request payload as JSON string or Python list/dict object.

    path_params : dict | None, default=None
        Replace placeholders like `{siteId}` in the URL path with actual values.

        Will be combined with [self.path_params](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.path_params) before sending request.

    headers : dict | None, default=None
        HTTP headers to be sent with the request.

        Will be combined with [self.headers](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.headers) before sending request.

    timeout : int | None, default=None
        Override the standard timeout timer [self.timeout](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.timeout) for a single request.

    Returns
    -------
    httpx.Response
        The [`httpx.Response`](https://www.python-httpx.org/api/#response) object from the request.
    """

    response = self.request(
        "PUT",
        path,
        data=data,
        params=None,
        path_params=path_params,
        headers=headers,
        timeout=timeout,
        is_auth_endpoint=False,
        auth=None,
    )

    return response

delete

delete(
    path: str,
    *,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None
) -> httpx.Response

Send an HTTP DELETE request to the specified path.

Parameters:

Name Type Description Default
path str

The API endpoint path to send the request to.

required
path_params dict | None

Replace placeholders like {siteId} in the URL path with actual values.

Will be combined with self.path_params before sending request.

None
headers dict | None

HTTP headers to be sent with the request.

Will be combined with self.headers before sending request.

None
timeout int | None

Override the standard timeout timer self.timeout for a single request.

None

Returns:

Type Description
Response

The httpx.Response object from the request.

Source code in src/wingpy/cisco/nexusdashboard.py
def delete(
    self,
    path: str,
    *,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
) -> httpx.Response:
    """
    Send an HTTP `DELETE` request to the specified path.

    Parameters
    ----------
    path : str
        The API endpoint path to send the request to.

    path_params : dict | None, default=None
        Replace placeholders like `{siteId}` in the URL path with actual values.

        Will be combined with [self.path_params](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.path_params) before sending request.

    headers : dict | None, default=None
        HTTP headers to be sent with the request.

        Will be combined with [self.headers](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.headers) before sending request.

    timeout : int | None, default=None
        Override the standard timeout timer [self.timeout](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.timeout) for a single request.

    Returns
    -------
    httpx.Response
        The [`httpx.Response`](https://www.python-httpx.org/api/#response) object from the request.
    """

    response = self.request(
        "DELETE",
        path,
        data=None,
        params=None,
        path_params=path_params,
        headers=headers,
        timeout=timeout,
        is_auth_endpoint=False,
        auth=None,
    )

    return response

get_page

get_page(
    path: str,
    offset: int,
    limit: int,
    *,
    params: dict | None = None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None
) -> httpx.Response

Retrieves a specific page of data from a GET endpoint.

Parameters:

Name Type Description Default
path str

The API endpoint path to send the request to.

required
offset int

Index of first items of the page.

required
limit int

The number of items to retrieve per page.

required
params dict | None

URL query parameters to include in the request. will be added as ?key=value pairs in the URL.

None
path_params dict | None

Replace placeholders like {objectId} in the URL path with actual values.

Will be combined with self.path_params before sending request.

None
headers dict | None

HTTP headers to be sent with the request.

Will be combined with self.headers before sending request.

None
timeout int | None

Override the standard timeout timer self.timeout for a single request.

None

Returns:

Type Description
Response

The httpx.Response object from the request.

Source code in src/wingpy/cisco/nexusdashboard.py
def get_page(
    self,
    path: str,
    offset: int,
    limit: int,
    *,
    params: dict | None = None,
    path_params: dict | None = None,
    headers: dict | None = None,
    timeout: int | None = None,
) -> httpx.Response:
    """
    Retrieves a specific page of data from a `GET` endpoint.

    Parameters
    ----------
    path : str
        The API endpoint path to send the request to.

    offset : int
        Index of first items of the page.

    limit : int
        The number of items to retrieve per page.

    params : dict | None, default=None
        URL query parameters to include in the request. will be added as `?key=value` pairs in the URL.

    path_params : dict | None, default=None
        Replace placeholders like `{objectId}` in the URL path with actual values.

        Will be combined with [self.path_params](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.path_params) before sending request.

    headers : dict | None, default=None
        HTTP headers to be sent with the request.

        Will be combined with [self.headers](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.headers) before sending request.

    timeout : int | None, default=None
        Override the standard timeout timer [self.timeout](https://wingpy.automation.wingmen.dk/api/nexusdashboard/#wingpy.cisco.NexusDashboard.CiscoNexusDashboard.timeout) for a single request.

    Returns
    -------
    httx.Response
        The [`httpx.Response`](https://www.python-httpx.org/api/#response) object from the request.
    """

    if isinstance(params, dict):
        params = params.copy()
    else:
        params = {}

    # Prepare params for the first page of data
    params["offset"] = offset
    params["max"] = limit

    rsp = self.get(
        path,
        params=params,
        path_params=path_params,
        headers=headers,
        timeout=timeout,
    )

    page = (offset // limit) + 1

    logger.debug(f"Retrieved page {page} from {path}.")

    return rsp

authenticate

authenticate() -> None

Executes the API-specific authentication process and records timestamps for session tracking.

Notes

Authentication will automatically be carried out just-in-time.

Only call this method directly if you need to authenticate proactively, outside of normal request flow.

Source code in src/wingpy/base.py
def authenticate(self) -> None:
    """
    Executes the API-specific authentication process and records timestamps
    for session tracking.

    Notes
    ----
    Authentication will automatically be carried out just-in-time.

    Only call this method directly if you need to authenticate proactively,
    outside of normal request flow.
    """

    # Authenticate
    logger.debug("Authenticating and recording token lifetime")
    auth_response = self._authenticate()

    # Record the time of authentication
    self.auth_timestamp = arrow.utcnow()

    self._after_auth(auth_response=auth_response)

tasks

tasks: TaskRunner = TaskRunner(max_workers=max_workers)

Manages concurrent requests to the API server.

The number of concurrent requests is limited by the MAX_CONNECTIONS property:

  • 1 connection is reserved for the main thread used for authentication and synchronous requests.
  • The remaining connections are used for concurrent requests.
See Also

wingpy.scheduling.TaskRunner Schedule and run asynchronous tasks in parallel.

is_authenticated

is_authenticated

Check if the client is authenticated.

timeout

timeout: int = timeout

The timeout in seconds for each request to the API server.

MAX_CONNECTIONS

MAX_CONNECTIONS = 20

The maximum number of concurrent connections opened to the Cisco Nexus Dashboard.

1 connection will be used for general synchronous requests.

6 connections will be used for parallel asynchronous requests.

RETRY_RESPONSES

RETRY_RESPONSES = []

No explicit retry reponses are defined for Cisco Nexus Dashboard.

headers

headers: dict = headers or {}

A dictionary of HTTP headers to be sent with each request. These headers will be merged with any headers dict passed to an individual request.

path_params

path_params: dict = {}

A dictionary of path parameters to be used in the API path of each request.

These parameters will be merged with any path_params dict passed to the request.