Skip to content

Python SDK

yousleep-common is the Python package for the youSleep Portal. It contains a typed, asynchronous client for the REST API, the Pydantic models every request and response is made of, and the tools an analysis container uses to read its manifest and write its output.

Version 43.0.0 · yousleep-common on PyPI

  • Analyse a file


    client.workflows uploads, submits, polls and fetches results in one call, for one file or a batch.

    Workflows

  • Use the client


    Projects, studies, recordings, analyses and reports are namespaces on the client. Every endpoint is typed with the same models the server validates against.

    SDK guide

  • Integrate a system


    Connect a device backend or study system that submits recordings on behalf of many subjects, and design around the platform's limits.

    Integration guide

  • Build an analysis


    yousleep-init writes a project that passes the conformance check as generated. Replace the method, run make verify, and register it.

    Packaging an analysis

Install

pip install yousleep-common

The package requires Python 3.11 or later and has three runtime dependencies (pydantic, httpx, pyyaml). An analysis container that only reads a manifest and writes a document can install it or read the JSON directly.

Quick start

A person authenticates with an email and a password. A machine uses an API key, created on the account page once an administrator has enabled keys for the account.

from yousleep_common.client import AsyncClient
from yousleep_common.models import UserAuthentication

client = await AsyncClient.from_credentials(
    base_url="https://api.yousleep.ai",
    credentials=UserAuthentication(email="you@example.com", password="…"),
)
import os

from yousleep_common.client import AsyncClient

client = AsyncClient.from_api_key(
    base_url="https://api.yousleep.ai", api_key=os.environ["YOUSLEEP_API_KEY"]
)

Then analyse a recording. The workflow helper creates the project and study it needs, uploads the file, waits for the run and returns the results:

async with client:
    result = await client.workflows.analyze_file(
        file="night.edf",
        analysis_config_id="u-sleep-research-v2",
        study_name="Subject 001",   # optional; inferred from the file name
        age=35, sex="male",         # optional subject metadata
    )
    print(result.biomarkers.biomarkers.tst_min, len(result.events))

result.events is the list of events the analysis produced, result.biomarkers the sleep statistics computed from them, and result.biomarkers.table the same numbers as the server presents them, formatted and labelled.

flowchart LR
    F[night.edf] --> U[upload]
    U --> S[submit]
    S --> P[poll]
    P --> R[events, statistics, tables]

Many files. analyze_files submits a batch and returns one outcome per file. A failing recording does not affect the others:

result = await client.workflows.analyze_files(
    files=["sub-01.edf", "sub-02.edf", "sub-03.edf"],
    analysis_config_id="u-sleep-research-v2",
)
for ok in result.succeeded:
    print(ok.file, ok.result.biomarkers.biomarkers.tst_min)
for bad in result.failed:
    print(bad.file, bad.status, bad.error)

Temporary runs. The _temporary variants delete the project, study, recording and analysis they created when the block exits, including on error:

async with client.workflows.analyze_file_temporary(
    file="night.edf", analysis_config_id="u-sleep-research-v2"
) as result:
    export(result.biomarkers)

Step by step. The workflows compose the namespaced endpoints and add no routes of their own. Anything they do not cover is available on the endpoints directly:

from pathlib import Path

from yousleep_common.models import AnalysisRequest, ProjectCreate, StudyCreate

project = await client.projects.create(ProjectCreate(name="Cohort 2026"))
study = await client.studies.create(project.id, StudyCreate(name="Subject 001"))
recording = await client.recordings.upload(study.id, Path("night.edf"))
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)

Errors and limits

Every error the SDK raises derives from YouSleepClientError, with one class per failure mode:

Exception When
AuthenticationError The token or key is missing, expired or wrong (401)
ValidationError The request did not match the model (422)
NotFoundError No such project, study, recording or analysis (404)
InsufficientCreditsError The account cannot reserve credits for the run (402)
QuotaExceededError A usage limit on projects, studies, analyses or storage is reached
RateLimitError Throttled (429), after the client's own retries with backoff
AnalysisWorkflowError The analysis ended failed or cancelled; carries its logs
ClientTimeoutError wait_for or a workflow ran past its timeout

Limits and current consumption can be read before submitting:

limits = await client.user.usage_limits()     # None where unlimited
usage = await client.user.usage_detailed()
print(usage.storage.active, "of", limits.storage.active, "bytes")

The models are the contract

yousleep_common.models and yousleep_common.types are the definitions the API server validates against, the SDK sends, and an analysis container reads and writes. A change to a contract is made in one place.

from yousleep_common.models import AnalysisRequest, Event, StudyCreate
from yousleep_common.types import AnalysisStatus, AnalysisType, EventLabel

The API reference is generated from those sources; an IDE resolves every signature offline from the installed package.

Versions

The client compares its own version with the API's on its first request and refuses an incompatible pair. Version pairing explains the policy and how to plan for it.

All pages

SDK guide Installing, authenticating, the shape of the client, errors
Workflows The end-to-end helpers in depth
Bulk operations Acting on many recordings or analyses by selector
Study metadata in bulk Ages, sexes and lights across a cohort in one call
Integration guide Connecting an external system, and the limits to design around
Version pairing How SDK and API versions are matched
Packaging an analysis Running your own analysis on the platform
Starting a project yousleep-init, the project generator
The manifest The document a container reads
The events document The document a container writes
Checking an image yousleep-verify, the conformance check
Package layout What lives where in the package