Quick Start¶
Initializing the Client and Logging-in¶
The fundamental class is 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:
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
login() method:
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:
>>> client.logout()
Using the Client as a Context Manager¶
The client can also be used as a context manager to ensure proper cleanup:
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¶
The Kelvin API client can be configured using environment variables. The following environment variables are supported:
Variable |
Description |
|---|---|
|
Base URL of the API (e.g., |
|
Username for authentication |
|
Password for authentication |
|
Time-based one-time password (if MFA is enabled) |
|
OAuth client ID (defaults to |
|
OAuth client secret (for service accounts) |
|
Number of retries for failed requests (default: 3) |
|
Request timeout in seconds (default: |
When environment variables are set, you can create a client without explicit parameters:
# 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:
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()
<Response [200]>
# 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:
# Get all status codes
>>> response_history.get_status_codes()
[200, 200, 201]
# Get successful responses only
>>> response_history.get_successful_responses()
[<Response [200]>, <Response [200]>, <Response [201]>]
# Get error responses
>>> response_history.get_error_responses()
[]
# Filter by status code
>>> response_history.filter_by_status_code(200)
[<Response [200]>, <Response [200]>]
# Filter by URL pattern
>>> response_history.filter_by_url_pattern("assets")
[<Response [200]>]
# 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:
>>> 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:
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:
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.