labapi.client.Client#
- class labapi.client.Client(
- base_url: str | None = None,
- akid: str | None = None,
- akpass: bytes | str | None = None,
- *,
- strict_cert: bool = True,
Bases:
objectA client for the LabArchives API.
This class handles the connection to the LabArchives API and provides methods for making authenticated API calls. It also manages the authentication flow.
- __init__(
- base_url: str | None = None,
- akid: str | None = None,
- akpass: bytes | str | None = None,
- *,
- strict_cert: bool = True,
Initialize a LabArchives API client.
If any parameter is None, the client will attempt to load values from a
.envfile usingpython-dotenv. The environment variables used are:API_URL: The base URL (defaults tohttps://api.labarchives.com).ACCESS_KEYID: The Access Key ID.ACCESS_PWD: The Access Key Password.
- Parameters:
base_url – The base URL of the LabArchives API (e.g., “https://mynotebook.labarchives.com”). If None, loaded from the
API_URLenvironment variable.akid – The Access Key ID for API authentication. If None, loaded from the
ACCESS_KEYIDenvironment variable.akpass – The Access Key Password for HMAC-SHA512 signing. If None, loaded from the
ACCESS_PWDenvironment variable.strict_cert – Whether to use strict X.509 certificate verification. If False, disables the VERIFY_X509_STRICT flag to allow connections to servers with certificates that may not pass strict validation. Defaults to True. Warning: Setting this to False reduces security.
Methods
__init__([base_url, akid, akpass, strict_cert])Initialize a LabArchives API client.
api_get(api_method_uri, **kwargs)Send a GET request and parse the XML response into an element.
api_post(api_method_uri, body, **kwargs)Send a POST request and parse the XML response into an element.
close()Close the underlying requests session.
collect_auth_response(*[, port, ...])Return a context manager for collecting a loopback auth callback.
construct_url(api_method_uri, query[, ...])Construct a fully qualified and signed URL for an API method.
default_authenticate(*[, port, timeout])Authenticate a user with the default browser and a loopback callback.
generate_auth_url(redirect_url)Generate a LabArchives login URL for the given callback.
login(user_email, auth_code)Log in a user with an authentication code.
raw_api_get(api_method_uri, **kwargs)Send a GET request and return the raw
requests.Response.raw_api_post(api_method_uri, body, **kwargs)Send a POST request and return the raw
requests.Response.stream_api_get(api_method_uri, **kwargs)Send a GET request and return a streamed response wrapper.
stream_api_post(api_method_uri, body, **kwargs)Send a POST request and return a streamed response wrapper.
- close() None[source]#
Close the underlying requests session.
Once closed, this client should not be used for further API requests. Any
Userobjects derived from this client should also be treated as no longer usable for API calls.
- generate_auth_url(redirect_url: str) str[source]#
Generate a LabArchives login URL for the given callback.
This URL is used to initiate the authorization code flow, redirecting the user to LabArchives to grant permissions.
- Parameters:
redirect_url – The URL to which LabArchives will redirect the user after successful authentication, containing the authorization code.
- Returns:
The full authentication URL.
- login( ) User[source]#
Log in a user with an authentication code.
This code can come from the standard browser flow or from a one-hour code generated in the LabArchives website.
This method exchanges the authorization code for user access information, including their user ID and available notebooks.
- Parameters:
user_email – The email address of the authenticating user.
auth_code – The authorization code received from LabArchives.
- Returns:
A
Userobject representing the authenticated user session.
- stream_api_get( ) StreamingResponse[source]#
Send a GET request and return a streamed response wrapper.
This is useful for downloading large files or when the response content needs to be processed incrementally.
- Parameters:
api_method_uri – The API method URI (e.g., “get_file_attachment”). Can be a string or a sequence of strings representing path segments.
kwargs – Additional query parameters to pass to the API method.
- Returns:
A
StreamingResponsewrapper with both an iterable byte stream and the fullrequests.Response.- Raises:
RuntimeError – If the client session has been closed.
AuthenticationError – If LabArchives rejects the request due to invalid or expired credentials.
ApiError – If LabArchives returns any other non-success response.
- stream_api_post( ) StreamingResponse[source]#
Send a POST request and return a streamed response wrapper.
This is useful for uploading large files or when the response content needs to be processed incrementally.
- Parameters:
api_method_uri – The API method URI (e.g., “upload_file_attachment”). Can be a string or a sequence of strings representing path segments.
body – The request body, which can be a mapping of form data or a file-like object.
kwargs – Additional query parameters to pass to the API method.
- Returns:
A
StreamingResponsewrapper with both an iterable byte stream and the fullrequests.Response.- Raises:
RuntimeError – If the client session has been closed.
AuthenticationError – If LabArchives rejects the request due to invalid or expired credentials.
ApiError – If LabArchives returns any other non-success response.
- raw_api_get( ) Response[source]#
Send a GET request and return the raw
requests.Response.This method is suitable for API calls where the full HTTP response, including headers and status code, is needed, and the content is not expected to be streamed.
- Parameters:
api_method_uri – The API method URI (e.g., “get_entry_data”). Can be a string or a sequence of strings representing path segments.
kwargs – Additional query parameters to pass to the API method.
- Returns:
The
requests.Responseobject containing the API response.- Raises:
RuntimeError – If the client session has been closed.
AuthenticationError – If LabArchives rejects the request due to invalid or expired credentials.
ApiError – If LabArchives returns any other non-success response.
- raw_api_post( ) Response[source]#
Send a POST request and return the raw
requests.Response.This method is suitable for API calls where the full HTTP response, including headers and status code, is needed, and the content is not expected to be streamed.
- Parameters:
api_method_uri – The API method URI (e.g., “create_entry”). Can be a string or a sequence of strings representing path segments.
body – The request body, which can be a mapping of form data or a file-like object.
kwargs – Additional query parameters to pass to the API method.
- Returns:
The
requests.Responseobject containing the API response.- Raises:
RuntimeError – If the client session has been closed.
AuthenticationError – If LabArchives rejects the request due to invalid or expired credentials.
ApiError – If LabArchives returns any other non-success response.
- api_get( ) Element[source]#
Send a GET request and parse the XML response into an element.
This is the primary method for retrieving structured data from the API.
- Parameters:
api_method_uri – The API method URI (e.g., “get_notebook_info”). Can be a string or a sequence of strings representing path segments.
kwargs – Additional query parameters to pass to the API method.
- Returns:
An
lxml.etree.Elementrepresenting the root of the XML response.- Raises:
RuntimeError – If the client session has been closed.
AuthenticationError – If LabArchives rejects the request due to invalid or expired credentials.
ApiError – If LabArchives returns any other non-success response.
Invalid XML propagates
lxml.etree.XMLSyntaxError.
- api_post( ) Element[source]#
Send a POST request and parse the XML response into an element.
This is the primary method for sending data to the API and receiving structured XML responses.
- Parameters:
api_method_uri – The API method URI (e.g., “create_entry”). Can be a string or a sequence of strings representing path segments.
body – The request body, which can be a mapping of form data or a file-like object.
kwargs – Additional query parameters to pass to the API method.
- Returns:
An
lxml.etree.Elementrepresenting the root of the XML response.- Raises:
RuntimeError – If the client session has been closed.
AuthenticationError – If LabArchives rejects the request due to invalid or expired credentials.
ApiError – If LabArchives returns any other non-success response.
Invalid XML propagates
lxml.etree.XMLSyntaxError.
- default_authenticate( ) User[source]#
Authenticate a user with the default browser and a loopback callback.
This method opens a browser window, directs the user to the LabArchives authentication page, and then listens on a loopback callback URL on
127.0.0.1:<port>for the redirect containing the authorization code. If no compatible browser is available, it falls back to printing the authentication URL to the terminal so the user can open it manually.Note
Automatic browser launching requires the optional
labapi[builtin-auth]dependencies.- Parameters:
port – The local callback port to listen on. Defaults to
8089.timeout – Maximum number of seconds to wait for a valid callback. Defaults to five minutes. Pass
Noneto wait indefinitely.
- Returns:
A
Userobject representing the authenticated user session.- Raises:
RuntimeError – If the client session has been closed.
ImportError – If automatic browser-based authentication is requested but the optional builtin-auth dependencies are not installed.
AuthenticationError – If authentication fails or times out.
- collect_auth_response( ) _AuthResponseCollector[source]#
Return a context manager for collecting a loopback auth callback.
The returned collector binds a local HTTP server on enter, waits for a valid callback via its
wait()method, and closes the server on exit.- Parameters:
port – The local callback port to listen on. Defaults to
8089.callback_path – The callback path to accept. Defaults to
/.timeout – Maximum number of seconds to wait for a valid callback. Defaults to five minutes. Pass
Noneto wait indefinitely.
- Returns:
An enterable collector with a
wait()method for the authentication callback.
- construct_url(
- api_method_uri: str | Sequence[str],
- query: Mapping[str, Any],
- expires_in: timedelta | datetime | None = None,
- *,
- should_prefix_api: bool = True,
- signature_method: str | None = None,
Construct a fully qualified and signed URL for an API method.
This method handles the assembly of the base URL, API method path, query parameters, and the HMAC-SHA512 signature required by the LabArchives API.
- Parameters:
api_method_uri – The API method URI (e.g., “get_notebook_info”). Can be a string or a sequence of strings representing path segments.
query – A dictionary of query parameters to include in the URL.
expires_in – The duration for which the URL should be valid. Can be a timedelta object or a specific datetime object. If None, defaults to 60 seconds from now.
should_prefix_api – If True, ensures the API method path starts with “api/”. Defaults to True.
signature_method – An optional string to use as the API method for signature generation, overriding api_method_uri. Useful for methods like api_user_login where the actual method name differs from the URI path.
- Returns:
The fully constructed and signed URL.
- Raises:
ValueError – If
api_method_uridoes not contain any non-empty path segments after normalization.