Accessing the REST API using a Python script

Procedure
  • To send requests to the REST API using a Python script, Hewlett Packard Enterprise recommends that you use an HTTP library.

    For example, the requests library is an HTTP library for Python that you can install using the following PIP command:

    pip install requests

    PIP is included with 3.4 or later version of Python.

    After you have installed the library, you can import the library into your Python script.

    Usage example:

    import requests
    ...
    r = requests.get('https://api.github.com/events')
    r.json()
    ...

    For more information, see:

    http://docs.python-requests.org/en/master/

  • In the part of the code that handles logging in, disable warnings about insecure requests.

    For example:

    # disable warnings that Web UI site is "insecure"
    # needed to avoid connection timeout due to inability to verify server certificate
    from requests.packages.urllib3 import disable_warnings
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    disable_warnings(InsecureRequestWarning)

    If you do not disable warnings about insecure requests, the request to log in hangs until the request times out because the server certificate could not be verified. An error similar to the following is returned:

    Connection timed out

  • In all requests, use the cookies parameter to pass the session cookie to the switch, and the verify=False parameter to disable server certificate verification.

    For example

            response = requests.post(
                    url=url,
                    cookies=self.cookie,
                    verify=False,
                )

    To avoid connection timeout errors because of the use of self-signed certificates, the Python script must include both the disable_warnings(InsecureRequestWarning) and verify=false in all requests.

    The session cookie is required to authenticate the request.

  • Ensure that the script logs out of the switch before exiting.

    Logging out at the end of the session is important because the number of concurrent HTTPS sessions per client and per switch are limited, and session cookies are not shared across devices and scripts.

  • You can program the process of logging in, storing and passing the session cookie, and error handling in a variety of ways.

    For a detailed example that handles errors and response codes, see Example: Logging in and logging out using Python.