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,
)[source]#

Bases: object

A 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,
)[source]#

Initialize a LabArchives API client.

If any parameter is None, the client will attempt to load values from a .env file using python-dotenv. The environment variables used are:

  • API_URL: The base URL (defaults to https://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_URL environment variable.

  • akid – The Access Key ID for API authentication. If None, loaded from the ACCESS_KEYID environment variable.

  • akpass – The Access Key Password for HMAC-SHA512 signing. If None, loaded from the ACCESS_PWD environment 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 User objects 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_email: str,
auth_code: str,
) 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 User object representing the authenticated user session.

stream_api_get(
api_method_uri: str | Sequence[str],
**kwargs: Any,
) 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 wrapper with both an iterable byte stream and the full requests.Response.

Raises:

RuntimeError – If the API request fails.

stream_api_post(
api_method_uri: str | Sequence[str],
body: Mapping[str, str] | BufferedIOBase,
**kwargs: Any,
) 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 wrapper with both an iterable byte stream and the full requests.Response.

Raises:

RuntimeError – If the API request fails.

raw_api_get(
api_method_uri: str | Sequence[str],
**kwargs: Any,
) 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.Response object containing the API response.

Raises:

RuntimeError – If the API request fails.

raw_api_post(
api_method_uri: str | Sequence[str],
body: Mapping[str, str] | BufferedIOBase,
**kwargs: Any,
) 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.Response object containing the API response.

Raises:

RuntimeError – If the API request fails.

api_get(
api_method_uri: str | Sequence[str],
**kwargs: Any,
) 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 Element representing the root of the XML response.

Raises:

RuntimeError – If the API request fails or the response is not valid XML.

api_post(
api_method_uri: str | Sequence[str],
body: Mapping[str, str] | BufferedIOBase,
**kwargs: Any,
) 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 Element representing the root of the XML response.

Raises:

RuntimeError – If the API request fails or the response is not valid XML.

default_authenticate(
*,
port: int = 8089,
timeout: float | None = 300.0,
) 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 detected, it falls back to printing the authentication URL to the terminal, requiring the user to manually open it.

Note

This method requires the selenium package for automatic browser control. Install it with: pip install selenium

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 None to wait indefinitely.

Returns:

A User object representing the authenticated user session.

Raises:
collect_auth_response(
*,
port: int = 8089,
callback_path: str = '/',
timeout: float | None = 300.0,
) _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 _AuthResponseCollector.wait(), 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 None to 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,
) str[source]#

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_uri does not contain any non-empty path segments after normalization.