Skip to content

Integration guide

This guide is for integrating an external system, such as a device backend, an EDC or a study-management application, that submits recordings to the youSleep platform and consumes the results programmatically. It covers the whole path and states the limits to design around.

If you are analysing your own files, read the SDK guide instead. This page assumes a server calling on behalf of many subjects.

Before you write code

Four requirements gate access, all of them administrative rather than technical.

Requirement How it is satisfied
An approved account Registration is request-access: a new account cannot log in until an administrator approves it
Accepted licence and terms Every authenticated route requires current consent; a key has a grace period after a new version, then fails on every endpoint
A usage type that matches your use Chosen at registration and changed only through an administrator; it determines which licence you are gated onto
Credits Research analyses are paid from the organisation's research grants, commercial ones from purchased credits. Confirm the balance, or ask for a grant, before designing a schedule around it

Confirm all four with your youSleep contact before integration work starts. They are the most common reason a correct client receives 401 or 403 on its first call.

Base URL and versions

https://api.yousleep.ai

The SDK refuses an API whose yousleep_common version differs from its own (version pairing), and the API is released independently of your backend. An integration on its own release cadence therefore needs a policy for taking SDK upgrades. strict_version_check=False is a short-term bridge, not a way to make a failing build pass.

Authentication

A machine authenticates with an API key: an opaque bearer credential that acts as the user account it belongs to, narrowed to the permissions it was scoped to.

from yousleep_common.client import AsyncClient

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

A key is created by a signed-in user on the portal's account page, or with the SDK. The full key is shown once; the platform stores only a hash and the first characters, so a lost key cannot be recovered, only replaced. Keys have the following properties:

  • Least privilege. Scope a key to what the integration needs, for example recording:create, analysis:create and analysis:read. The server lists the permissions a key may carry (GET /status/permissions, key_scopeable) and refuses any other. Account and key management are never among them, so a leaked key cannot change the password, accept legal documents, buy credits or mint further keys. A key never holds more than its owner: withdrawing a permission from the account narrows every key at once.
  • Every key expires. The server caps the lifetime and applies a default when none is given. Rotate by creating the next key before the current one lapses, switching over, then deleting the old one. The owner is emailed seven days before a key expires.
  • Revocation is immediate. Deleting a key, disabling the account, or an administrator's revocation stops it on the next request.
  • Failures are deliberately uniform. An unknown, revoked or expired key answers 401 with the same body; the account page shows a key's state. A 403 means the key authenticated but lacks the scope, or the account's consent has lapsed.
  • Consent has a grace period for machines. After a new version of the terms or a licence, a person accepts it on their next sign-in, while a key keeps working for a grace period. Its responses carry an X-Consent-Deadline header naming when it stops; log it. The owner is also emailed a week before the deadline.
  • Rate limits are per key. A busy pipeline does not lock its owner out of the portal, and two keys do not share a window.
  • Attribution. Content the key creates belongs to the owning account like anything else; the audit trail records which key acted.

Hold the key in a secret manager on your backend, never in a browser, a mobile app or device firmware: a key identifies the account it belongs to. A person exploring the API signs in with an email and password instead (AsyncClient.from_credentials); those sessions are short-lived by design and the wrong credential for an unattended process.

The resource model

Project ─┬─ Study ── Recording ── Analysis ── Events / Biomarkers
         └─ Study ── Recording ── Analysis ── …

Items are addressed by their own UUID and collections by their parent's (SDK guide); names are never looked up. client.recordings.list_for_project(project_id) reads a project's recordings across all of its studies, each carrying its study's id and name.

Two properties of the model affect how an integration is designed:

  • A study holds one recording. One file is one study.
  • A subject is identified by a key rather than a record. Studies of one person share a subject_key (compared case- and whitespace-insensitively) and optionally a session_index. Per-subject figures, series and erasure use these fields. Set both when creating studies, or afterwards in bulk; see study metadata in bulk.

Studies also accept age, sex, bmi and tags. Tags are the grouping axis of project reports, so studies tagged with their arm or cohort can be compared without further modelling.

The expected topology: recordings reach your own systems first, and your backend holds the key and talks to the platform.

flowchart LR
    D[Recorder or device] --> Y[Your backend]
    Y -- upload --> P[youSleep API]
    P --> A[analyses]
    A -- events, statistics --> Y

Getting data in

client.recordings.upload(study_id, Path("night.edf")) pre-registers the recording with its EDF header, streams the file to a presigned PUT in 64 KiB chunks, and finalises. The bytes go from the calling machine straight to storage. A recording held in your own object store is fetched by your backend and uploaded the same way, unless your organisation keeps its recordings in its own bucket (below).

The PUT sends the headers in presigned_upload.headers, which are signed into the URL. Among them, If-None-Match: * lets the URL create the object once: a second PUT is refused with 412, so nothing can replace a recording after it is checked. A client uploading without this SDK sends them too, and treats a 412 on a retry as the object already stored.

The upload follows its project's pseudonymisation policy, which is set when the project is created (ProjectCreate.pseudonymisation):

  • The EDF patient and recording identification fields are blanked in every project. If the project removes dates (dates="removed"), the start date becomes EDF+'s unknown date; the time of day stays. Only the uploaded copy's first 256 bytes are rewritten; your file is not changed.
  • In a project that codes file names (file_names="coded"), youSleep issues the codes and refuses any other name (name_not_issued). Create each study under a code from client.projects.issue_codes(project_id, count) and keep your own map of file to code; the recording carries its study's code and the file's extension. The workflows and the in-place registrations ask for codes themselves, and their results pair each file with its code. youSleep knows which codes it issued, never which file one stands for.

A client that uploads without this SDK applies the rule itself, with yousleep_common.edf.pseudonymise_header as the reference (EDF headers).

Your organisation's own bucket and hardware

An organisation can run its analyses on its own hardware, with youSleep's runner, and keep a project's recordings in its own S3-compatible bucket. Each is a capability that youSleep turns on once the organisation's owner has asked for it and accepted the site agreement. A bucket needs the organisation's own hardware as well, because only its runner reads the bucket. For a project whose recordings are in the bucket, three things change:

  • Where the bytes go. An upload goes to the bucket, not to youSleep's storage, and a file already in the bucket is registered where it is, without a copy.
  • Where the calls run. The bucket answers only on the organisation's network, so whatever uploads, lists or registers its files runs there.
  • What youSleep receives. Each recording's cleaned header, its annotations without their free text, and the results. The signals stay in the bucket.

The SDK guide has the calls, from the capabilities to registering files in place, and Set up a site the steps in order.

Submitting and collecting results

from yousleep_common.models import AnalysisRequest

analysis = await client.analyses.submit(
    recording.id, AnalysisRequest(analysis_config_id="u-sleep-research-v2")
)
analysis = await client.analyses.wait_for(analysis.id, timeout=3600)
events = await client.analyses.get_events(analysis.id)
biomarkers = await client.analyses.get_biomarkers(analysis.id)

client.analyses.list_configs() returns the analyses available to you, each with its input requirements (accepted format, channel types, minimum duration), its price per hour of signal (credits_per_signal_hour) and the balance that pays for it (spend_class). Validate recordings against the config you intend to run rather than discovering a mismatch at submission. Its site_allowance says whether it may run where your organisation's analyses run (place, runs_there), and by_exception when only an exception youSleep recorded allows it at your site. client.analyses.list_publications() returns the publications behind the analyses, grouped by family.

client.analyses.quote(recording.id, request) takes the same request as submit and returns what the analysis would cost, the balance it would be drawn from, and blocked_reason when the submission would be refused. It creates nothing and reserves no credits. A request that submission would reject fails the quote in the same way, so a quote also checks a request before it is sent.

Reading events at scale

get_events returns a flat list[Event], convenient for iterating over one analysis but the wrong form for a pipeline: a night of 1 Hz sleep staging is tens of thousands of events, per analysis, per night, per subject. There are two ways round it.

Fetch blocks instead. Blocks encode the same events as runs of consecutive equal-duration slots, with per-slot attributes as parallel arrays: a night is a handful of blocks.

from yousleep_common.utils.event_blocks import blocks_to_events

document = await client.analyses.get_event_blocks(analysis.id)
document.event_count            # without materialising anything
events = blocks_to_events(document.blocks)   # only if you need them flat

The document is returned whole, without server-side filtering, so fetch it once and slice locally. The encoding is lossless for any event list: irregular, overlapping or single events become one-slot blocks. client.batch.get_event_blocks fetches one document per analysis in one request, up to the server's per-request cap, unfiltered too.

from yousleep_common.models import BatchGetEventBlocksRequest

response = await client.batch.get_event_blocks(
    project.id, BatchGetEventBlocksRequest(analysis_ids=[a.id, b.id])
)
for entry in response.results.values():
    if entry.status == "ok" and entry.document is not None:
        events = blocks_to_events(entry.document.blocks)

Or filter and page the flat endpoint. get_events narrows on the server: a time window in milliseconds from the recording start, a label or an analysis type to keep or remove, then offset and limit. Without a limit, the client reads every page.

from yousleep_common.types import AnalysisType

first_hour = await client.analyses.get_events(
    analysis.id, window_end_time_ms=3_600_000, analysis_type=AnalysisType.STAGING
)

Sporadic events such as arousals and limb movements are sparse enough for the flat form; dense per-epoch output is where blocks matter.

Results are presentation-complete: the API computes the statistics, their formatting, the tables and the chart geometry, so two renderers of one payload draw the same thing. Take the values as given rather than recomputing them.

Working at volume

Use the batch endpoints rather than looping. They accept up to 500 items per request and return 207 Multi-Status with a per-item result, so one bad recording does not abort the batch.

Operation Method
Create studies client.batch.create_studies
Price before submitting client.batch.quote_analyses (one recording: client.analyses.quote)
Submit analyses client.batch.submit_analyses
Poll many analyses client.batch.get_analyses_status
Fetch events client.batch.get_events — flat list[Event] per analysis
Fetch event blocks client.batch.get_event_blocks — one block document per analysis; prefer this for dense output, see Reading events at scale
Write subject metadata client.batch.patch_studies_metadata

Two behaviours of the batch endpoints affect how a client is written:

  • A 207 does not mean success. Read every item's status; the summary object carries the counts when you only need to know whether to look closer.
  • Submission is accepted item by item, not all or nothing. Accepted items start running while later ones are still being processed, and an interrupted client keeps everything already accepted. Re-submitting is safe: accepted items come back as per-item duplicate errors rather than running twice.

client.workflows.analyze_files(...) composes create, upload, submit and poll into one call with per-file outcomes (Workflows). Use it for straightforward cases, and the batch endpoints when you need control over each step.

Limits to design around

Rate limits are enforced per credential: each API key has its own budget, and so does each person signed in. A key shared across a fleet shares one budget for all of it, the most common surprise when moving from a pilot to production volume.

Limit Scope Notes
Uploads per credential, per day Each recording registered for upload draws on the daily budget
Batch submission per credential Rate-limited per request, with a 500-item ceiling per request
Reads per credential Sized for per-analysis polling, but prefer the batch status endpoint to per-analysis loops
Storage per organisation A ceiling in bytes, not a rolling quota — deleting recordings frees it
Credits per organisation Reserved at submission and settled at completion. client.batch.quote_analyses says what a batch costs and which balance pays
Projects per organisation A flat cap

Read the live values with client.organizations.get_usage(org_id) rather than hard-coding them. Responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. The SDK retries throttled requests with exponential backoff; quota and credit errors are raised immediately, because retrying them cannot succeed.

Errors

Every SDK error derives from YouSleepClientError, with one class per failure mode (the list). Batch responses carry the same vocabulary per item as a machine-readable error.code, so one taxonomy covers both call styles.

What the platform does not do yet

The following are not available, so an integration should not depend on them:

  • No webhooks or result callbacks. Completion is discovered by polling; the batch status endpoint is the efficient way to do it.
  • No service accounts. A key belongs to a person's account and acts as it; an integration's key is owned by the person who created it.
  • No cross-organisation sharing. A project is shared within its organisation only, and an account belongs to exactly one organisation. Collaborating with a second organisation needs a second account.

If an integration needs any of these, raise it with us early. Several are open design questions rather than settled decisions.