=========== Quick Start =========== Initializing the Client and Logging-in -------------------------------------- The fundamental class is :obj:`kelvin.api.client.Client`, which authenticates users to the API and provides the main point of entry to the various objects and functions in the Kelvin API. The client can be initialized by providing the ``url``, ``username``, and ``password``: .. code-block:: ipython3 :caption: Initializing and logging-in the client: from kelvin.api.client import Client client = Client( url="https://yoyodyne.kelvininc.com", username="fox.mulder", password="trustno1" ) >>> client Client(url='https://yoyodyne.kelvininc.com') >>> client.user.get_user_me() UserMeGet( created=datetime.datetime(2019, 10, 29, 20, 50, 34, 801000, tzinfo=datetime.timezone.utc), email='fox.mulder@kelvininc.com', first_name='Fox', id=UUID('f35f15c9-ae91-4165-9610-dd02f4dadb6e'), last_name='Mulder', username='fox.mulder', permissions=['kelvin.permission.asset.read', ...], groups=['users']) If you need to log in after client creation (e.g., to update credentials), use the :meth:`~kelvin.api.client.Client.login` method: .. code-block:: ipython3 :caption: Logging-in after client creation: client.login(password="newpassword123") .. note:: The ``login`` method accepts keyword-only arguments: ``password``, ``totp`` (for time-based one-time passwords), and ``client_secret`` (for service accounts). Optionally, the client can be logged-out, which invalidates the access token and closes the connection: .. code-block:: ipython3 :caption: Logging-out the client: >>> client.logout() Using the Client as a Context Manager ------------------------------------- The client can also be used as a context manager to ensure proper cleanup: .. code-block:: ipython3 :caption: Using the client as a context manager: from kelvin.api.client import Client with Client( url="https://yoyodyne.kelvininc.com", username="fox.mulder", password="trustno1" ) as client: user = client.user.get_user_me() print(user.username) # Client is automatically closed when exiting the context .. _configuration: Configuration ------------- The Kelvin API client can be configured using environment variables. The following environment variables are supported: .. list-table:: Environment Variables :header-rows: 1 :widths: 40 60 * - Variable - Description * - ``KELVIN_CLIENT__URL`` - Base URL of the API (e.g., ``https://yoyodyne.kelvininc.com``) * - ``KELVIN_CLIENT__USERNAME`` - Username for authentication * - ``KELVIN_CLIENT__PASSWORD`` - Password for authentication * - ``KELVIN_CLIENT__TOTP`` - Time-based one-time password (if MFA is enabled) * - ``KELVIN_CLIENT__CLIENT_ID`` - OAuth client ID (defaults to ``kelvin-client``) * - ``KELVIN_CLIENT__CLIENT_SECRET`` - OAuth client secret (for service accounts) * - ``KELVIN_CLIENT__RETRIES`` - Number of retries for failed requests (default: 3) * - ``KELVIN_CLIENT__TIMEOUT`` - Request timeout in seconds (default: ``(6, 10)`` for connect/read) When environment variables are set, you can create a client without explicit parameters: .. code-block:: ipython3 :caption: Using environment variables: # With KELVIN_CLIENT__URL, KELVIN_CLIENT__USERNAME, and KELVIN_CLIENT__PASSWORD set from kelvin.api.client import Client client = Client() Troubleshooting --------------- If you run into issues, there are some methods for determining what might be causing the problem. Response History ~~~~~~~~~~~~~~~~ To track and debug API requests, you can use the ``ResponseHistory`` and ``RequestHistory`` plugins. These must be passed to the client during initialization: .. code-block:: ipython3 :caption: Setting up response history: from kelvin.api.client import Client from kelvin.api.base.http_tools import ResponseHistory, RequestHistory response_history = ResponseHistory(maxlen=50) request_history = RequestHistory(maxlen=50) client = Client( url="https://yoyodyne.kelvininc.com", username="fox.mulder", password="trustno1", plugins=[response_history, request_history] ) # Make some requests assets = client.asset.list_assets() # Get the latest response >>> response_history.latest() # Get response details >>> response = response_history[-1] >>> response.status_code 200 >>> response.url URL('https://yoyodyne.kelvininc.com/api/v4/assets/list?page_size=10000') >>> response.json() {'data': [...], 'pagination': {...}} The history classes provide several useful methods: .. code-block:: ipython3 :caption: History methods: # Get all status codes >>> response_history.get_status_codes() [200, 200, 201] # Get successful responses only >>> response_history.get_successful_responses() [, , ] # Get error responses >>> response_history.get_error_responses() [] # Filter by status code >>> response_history.filter_by_status_code(200) [, ] # Filter by URL pattern >>> response_history.filter_by_url_pattern("assets") [] # Clear history >>> response_history.clear() Dry-Run ~~~~~~~ Each API method has a ``_dry_run`` optional argument which will show what request would be sent to the server without actually making the request: .. code-block:: ipython3 :caption: Dry-run example: >>> client.asset.delete_asset(asset_name="asset_01", _dry_run=True) {'path': '/api/v4/assets/asset_01/delete', 'method': 'post', 'data': None, 'params': {}, 'files': {}} >>> client.asset.create_asset( ... data={"name": "new_asset", "asset_type_name": "well"}, ... _dry_run=True ... ) {'path': '/api/v4/assets/create', 'method': 'post', 'data': {'name': 'new_asset', 'asset_type_name': 'well'}, 'params': {}, 'files': {}} Verbose Mode ~~~~~~~~~~~~ For detailed logging of all requests and responses, enable verbose mode: .. code-block:: ipython3 :caption: Verbose mode: client = Client( url="https://yoyodyne.kelvininc.com", username="fox.mulder", password="trustno1", verbose=True ) This will log request and response details to the console for debugging purposes. Async Client ------------ For asynchronous applications, use the ``AsyncClient``: .. code-block:: ipython3 :caption: Using the async client: import asyncio from kelvin.api.client import AsyncClient async def main(): async with AsyncClient( url="https://yoyodyne.kelvininc.com", username="fox.mulder", password="trustno1" ) as client: user = await client.user.get_user_me() print(user.username) asyncio.run(main()) Kelvin Documentation -------------------- You can check examples of interaction with the client at `Kelvin Documentation `_.