Skip to content

SDK guide

This guide covers connecting to the API, the conventions every namespace of the client follows, reading results, an organisation's own hardware, and errors. The overview has the quick start and the API reference has every signature.

Connect

pip install yousleep-common     # or: uv add yousleep-common
from yousleep_common.client import AsyncClient
from yousleep_common.models import UserAuthentication

client = await AsyncClient.from_credentials(
    base_url="https://api.yousleep.ai",
    # The email and password you sign in to the portal with.
    credentials=UserAuthentication(email="me@example.com", password="…"),
)
async with client:
    me = await client.user.get_current()

from_credentials signs in and keeps the session refreshed, keeping each rotated refresh token in place of the last. client.auth.login() only returns a token pair; it does not authenticate the client it was called on. client.auth.logout(refresh_token) ends a session, and everywhere=True every session of the account.

An account that signs in with a second factor (an authenticator app's codes) cannot sign in this way: login() raises SecondFactorRequiredError after the password step. A script uses an API key instead, which takes no second factor.

from yousleep_common.client import AsyncClient

client = AsyncClient.from_api_key(base_url="https://api.yousleep.ai", api_key="ysk_…")

A key is never refreshed: a 401 means it is unknown, revoked or expired. The integration guide covers scoping, expiry and rotation.

Always use the client as a context manager, because it owns the HTTP connection pool.

Managing keys. Keys are managed from a signed-in session, never from a key:

from yousleep_common.models import ApiKeyCreate
from yousleep_common.types import Permission

async with await AsyncClient.from_credentials(base_url=..., credentials=...) as me:
    created = await me.user.create_api_key(
        ApiKeyCreate(
            name="Nightly pipeline",
            scopes=[Permission.RECORDING_CREATE, Permission.ANALYSIS_CREATE],
            expires_in_days=90,
            password="…",          # the account password, entered again
            code="123456",         # the app's current code, with a second factor
        )
    )
    created.secret                 # shown once; store it now
    await me.user.list_api_keys()  # name, prefix, scopes, expiry, last use
    await me.user.revoke_api_key(created.id)

Versions. On its first request the client compares its own version with the API's and raises ClientConnectionError on a mismatch, because the two are paired. strict_version_check=False turns the error into a warning and verify_connection=False skips the check; use either only briefly.

The shape of the client

Every area of the API is a namespace on the client:

analyses · auth · batch · billing · legal · organizations · projects · recordings · report_exports · reports · status · studies · user · workflows

A few routes are left out of the client because they belong to the web app alone: conversations with youSleep's staff, accepting the legal documents at sign-up, registering and checking an organisation's bucket, and the platform operators' administration routes. A runner's own requests are made by the runner. Every other route the API publishes has a method.

Three conventions apply to every namespace.

Writes take a request model rather than keyword arguments.

from yousleep_common.models import ProjectCreate

project = await client.projects.create(ProjectCreate(name="Cohort 2026"))

Items take their own id; collections take their parent's. A study, recording or analysis is addressed by its UUID alone. Listing or creating under a parent takes that one parent id. A name in an id position returns 422; names are not looked up.

studies = await client.studies.list(project.id)
recordings = await client.recordings.list(study.id)
analysis = await client.analyses.submit(recording.id, request)
events = await client.analyses.get_events(analysis.id)

A list method returns the whole list. Where the server serves a list a page at a time, the client reads page after page, at the largest page the server allows, until it has every item. A project of up to 10,000 studies, or one night's events, is one request. Pass limit (with skip or offset) to read one page instead, and use a count method to learn how many there are without fetching them.

A summary answers without the list. client.studies.summary(project_id) returns every tag and subject in a project with its count, the untagged studies and the first studies of each set, and stays small at any project size. tags_any also counts the studies a tag selection leaves out.

Everything belongs to your organisation. An account belongs to exactly one organisation, created with the account, which becomes a team when a colleague is invited.

  • Projects, storage and credits belong to the organisation. client.user.get_organization() returns it with your role, and client.organizations manages members, invitations and ownership.
  • A project is opened to every member, or shared with named colleagues, through its visibility and client.projects.share. Inside it everyone can add content; each person can change what they added, and the project's owner anything. The refusals are not_resource_owner and forbidden.
  • An API key reaches only the projects its owner owns.
  • The audit trail records what happened, and each event names who may read it. list_audit and export_audit (CSV) read it on client.organizations, client.projects and client.user, filtered by AuditFilters, with a signed-in session rather than a key. client.status.audit_actions() lists every event type and its readers.
  • Research analyses are paid from research grants; commercial analyses, and storage above the free ceiling, from purchased credits. client.billing.credits() returns both balances. client.organizations lists the grants (list_grants), prices a plan of analyses as its runs would be priced (estimate_credits), and asks for a grant or more time on one (request_grant, request_extension, list_credit_requests).
flowchart LR
    O[Organisation] --> P1[Project: private]
    O --> P2[Project: open to members]
    O --> P3[Project: shared with named colleagues]
    P2 --> S[Studies, recordings, analyses<br/>each with an owner]

Reading results

Events are the analysis's output; statistics, tables and figures are computed from them on the server so that every renderer draws the same thing.

  • client.analyses.get_events(id) returns the flat list, for iterating over one analysis.
  • client.analyses.get_event_blocks(id) returns the same content as a block document, a handful of blocks for a night; blocks_to_events decodes it. The integration guide says when to use each.
  • client.analyses.get_biomarkers(id) returns the sleep statistics with their presentation table. client.reports returns the same over a study or a project.

Project report origins

A large project report deduplicates per-study provenance: identical origins lists travel once on the envelope and are referenced per entry. Read them through report.resolve_origins(entry), which returns the effective list for either representation.

Your organisation's own hardware

An organisation can run its analyses on its own hardware and keep its recordings in its own bucket. The integration guide says what that changes for an integration, and Set up a site gives the steps in order. The calls below do what the organisation's Compute page does.

They take the organisation's id and need a signed-in session, since an API key cannot carry the permissions they need. A caller outside the organisation gets NotFoundError, one whose role may not act ForbiddenError, and a refusal named below by its code is a ConflictError (409) carrying it as error.code, unless another status is given. The list methods take limit (50 by default, up to 200) and offset, and return one page with its total.

Capabilities and the site agreement. Any member reads them. The owner alone accepts the agreement and asks for a capability.

from yousleep_common.models import CapabilityRequestCreate
from yousleep_common.types import SiteCapability

org = await client.user.get_organization()
caps = await client.organizations.get_capabilities(org.id)
for status in caps.capabilities:
    print(status.capability, status.state)        # off, requested or on

agreement = await client.legal.site_agreement()   # the latest version
if caps.acceptance is None or caps.acceptance.version != agreement.version:
    await client.organizations.accept_site_agreement(org.id, agreement.version)

await client.organizations.request_capability(
    org.id,
    CapabilityRequestCreate(
        capability=SiteCapability.SITE_COMPUTE, note="Analyses on our own servers"
    ),
)
requests = await client.organizations.list_capability_requests(org.id)

Only the latest published version can be accepted (site_agreement_not_current); while none is published, both agreement calls raise NotFoundError. There is one request per capability at a time (capability_already_requested), and none for a capability that is on (capability_already_on).

The site pool. While site compute is on, the owners and admins run the organisation's site pool: the runners that take its jobs. The first enrolment token creates it.

token = await client.organizations.create_enrolment_token(
    org.id, EnrolmentTokenCreate(password="…")  # and code="123456", with a second factor
)
token.token             # shown in this answer only; single use, until expires_at
token.storage_origins   # the storage addresses the runner reaches
token.runner_image      # the runner image to install, by digest

pool = await client.organizations.get_compute_pool(org.id)   # None before a token
pool.queued             # jobs waiting for a runner
pool.held               # jobs its runners hold
pool.runner_seen        # whether one of its runners is taking work

A token is refused while site compute is off (site_compute_off).

Runners. A runner enrols as pending. Approve it with the whole fingerprint, SHA256:…, which its fingerprint command prints on its host: the list shows only the last characters (fingerprint_hint), and an approval whose fingerprint differs is refused.

page = await client.organizations.list_runners(org.id)
for runner in page.items:
    print(runner.name, runner.state, runner.fingerprint_hint, runner.taking_work)

await client.organizations.approve_runner(
    org.id, runner.id, fingerprint="SHA256:…", password="…"  # and code=, as above
)
await client.organizations.revoke_runner(org.id, runner.id)

Revocation is final: the runner is refused from its next request on, and its jobs are taken back. Only youSleep releases a quarantined runner (quarantined_at), so ask on the Compute page: release_runner is refused (403, runner_release_by_yousleep). The page also names the current runner release and the lowest version handed work, and each runner says why it is handed only some kinds of job, or none (limited_by, passed_over). RunnerListResponse and RunnerOut describe every field; Operate the runner says how to fix each state on the host.

Run records. Every lease a runner of the pool held leaves a record when it ends: of an analysis, an ingest of a recording, or a delete in the organisation's bucket.

from yousleep_common.types import LeaseKind

records = await client.organizations.list_run_records(org.id, kind=LeaseKind.ANALYSIS)
for record in records.items:
    print(record.analysis_id, record.ended, record.runner_version, record.image_digest)

A record says how the lease ended (result, returned with its return_reason, or lapsed). Only an accepted result says what ran: the image digest, the SHA-256 of the inputs and output, the peak memory and the run length.

Files in the bucket. In a project whose recordings are in the bucket, client.recordings.upload puts the file there, and a file already there is registered where it is, without a copy. These calls reach the bucket, so they run on the organisation's network.

files = await client.projects.bucket_files(project.id, "nights/")   # in key order
await client.recordings.register_files_in_place(project.id, files)  # 100 to a request

found = await client.projects.new_bucket_files(project.id)
for folder, new in found.items():
    await client.recordings.register_files_in_place(project.id, new, folder=folder)

register_in_place registers one file. Each file becomes a study named after it, made valid and numbered when the project already has the name. new_bucket_files lists again every folder the project registered from, however many files it holds.

Errors

Every exception derives from YouSleepClientError, with one class per failure mode. The overview lists them. Two deserve attention:

from yousleep_common.client.exceptions import (
    ClientTimeoutError,       # NOT the builtin TimeoutError
    ClientConnectionError,
)

analyses.wait_for and the workflows raise ClientTimeoutError when their timeout elapses; except TimeoutError does not catch it.