Skip to content

Index

YouSleep Python SDK Client.

Provides a type-safe, async HTTP client for interacting with the YouSleep API.

Example
from yousleep_common.client import AsyncClient
from yousleep_common.models import ProjectCreate

async with AsyncClient(base_url="https://api.yousleep.ai", token="your-token") as client:
    # List projects
    projects = await client.projects.list()

    # Create a new project
    project = await client.projects.create(
        ProjectCreate(name="My Study", description="Sleep analysis")
    )

    # Get project details
    project = await client.projects.get(project.id)

AnalysisWorkflowError

Bases: YouSleepClientError

Raised by workflow helpers when an analysis ends in a non-completed terminal state.

__init__(message, *, analysis, logs=None)

Initialize the error.

Parameters:

Name Type Description Default
message str

Human-readable description of the failure.

required
analysis AnalysisOut

The analysis in its (non-completed) terminal state.

required
logs AnalysisLogs | None

Execution logs if they could be fetched, else None.

None

AnalysisWorkflowResult dataclass

Everything an end-to-end analyze_file produced.

events/biomarkers/report are populated according to the fetch argument (biomarkers only when the analysis produced sleep staging).

analysis_id property

UUID of the completed analysis.

recording_id property

UUID of the uploaded recording.

AsyncClient

Async HTTP client for the YouSleep API.

Provides type-safe methods for all API endpoints with automatic error handling, authentication, and retry logic.

Example
# Initialize with token
client = AsyncClient(
    base_url="https://api.yousleep.ai",
    token="your-jwt-token"
)

# Use as context manager (recommended)
async with AsyncClient(base_url="...", token="...") as client:
    projects = await client.projects.list()

# Or authenticate with credentials
from yousleep_common.models import UserAuthentication

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

admin cached property

Access admin-related endpoints (requires admin role).

analyses cached property

Access analysis-related endpoints.

auth cached property

Access authentication-related endpoints.

batch cached property

Access batch operation endpoints.

billing cached property

Access billing and payment endpoints.

legal cached property

Access legal document and license endpoints.

organizations cached property

Access organization, membership and invitation endpoints.

projects cached property

Access project-related endpoints.

recordings cached property

Access recording-related endpoints.

report_exports cached property

Access report export creation, polling and history endpoints.

reports cached property

Access report generation endpoints.

status cached property

Access status-related endpoints.

studies cached property

Access study-related endpoints.

user cached property

Access user-related endpoints.

workflows cached property

Access high-level end-to-end analysis workflows.

__aenter__() async

Enter async context manager.

__aexit__(exc_type, exc_val, exc_tb) async

Exit async context manager.

__init__(base_url, token=None, refresh_token=None, api_key=None, timeout=30.0, max_retries=3, verify_connection=True, strict_version_check=True)

Initialize the async client.

Parameters:

Name Type Description Default
base_url str

Base URL of the API (e.g., "https://api.yousleep.ai")

required
token str | None

JWT access token for authentication

None
refresh_token str | None

JWT refresh token for automatic token refresh

None
api_key str | None

An API key (ysk_…) created on the account page. Sent as the bearer credential in place of a session token; it never expires mid-run and is never refreshed. Exclusive with token and refresh_token.

None
timeout float

Request timeout in seconds

30.0
max_retries int

Maximum number of retry attempts for failed requests

3
verify_connection bool

Check connection health on first request (default: True)

True
strict_version_check bool

Fail if SDK and API yousleep_common versions don't match (default: True). If False, only warns on mismatch.

True

close() async

Close the HTTP client and cleanup resources.

delete(path, **kwargs) async

Make a DELETE request.

from_api_key(base_url, api_key, **kwargs) classmethod

Create a client that authenticates with an API key.

The machine counterpart of from_credentials: no sign-in round trip, because a key is presented directly as the bearer credential. The key is never refreshed; a 401 means it is unknown, revoked or expired.

Parameters:

Name Type Description Default
base_url str

Base URL of the API

required
api_key str

An API key (ysk_…) created on the account page

required
**kwargs Any

Additional arguments passed to AsyncClient constructor

{}

Returns:

Type Description
AsyncClient

A client ready to use — enter it as an async context manager

Example
client = AsyncClient.from_api_key(
    base_url="https://api.yousleep.ai", api_key=os.environ["YOUSLEEP_API_KEY"]
)
async with client:
    projects = await client.projects.list()

from_credentials(base_url, credentials, **kwargs) async classmethod

Create a client by authenticating with credentials.

Parameters:

Name Type Description Default
base_url str

Base URL of the API

required
credentials UserAuthentication

User authentication credentials (email and password)

required
**kwargs Any

Additional arguments passed to AsyncClient constructor

{}

Returns:

Type Description
AsyncClient

Authenticated AsyncClient instance

Raises:

Type Description
AuthenticationError

If authentication fails

Example
from yousleep_common.models import UserAuthentication

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

get(path, **kwargs) async

Make a GET request.

get_response(path, **kwargs) async

Make a GET request and return the raw response (headers + body).

Same auth/retry machinery as :meth:get; for callers that read response headers such as X-Total-Count.

get_text(path, **kwargs) async

Make a GET request and return the raw response body as text.

For non-JSON endpoints (e.g. the report audit CSV); goes through the same auth/retry machinery as :meth:get.

patch(path, **kwargs) async

Make a PATCH request.

post(path, **kwargs) async

Make a POST request.

put(path, **kwargs) async

Make a PUT request.

AuthenticationError

Bases: YouSleepClientError

Authentication failed (401 Unauthorized).

BatchAnalysisWorkflowResult dataclass

Everything a multi-file analyze_files run produced.

Per-file failures never raise (mirroring the platform's 207-style batch semantics); inspect :attr:failed for files that did not complete.

failed property

Outcomes that failed or timed out.

succeeded property

Outcomes whose analysis completed successfully.

FileAnalysisOutcome dataclass

Outcome for a single input file of :meth:WorkflowsEndpoint.analyze_files.

status is "completed" when the file's analysis finished successfully (result is set), "failed" when any stage failed for this file (error describes it; analysis is attached when one was submitted), and "timeout" when the analysis was still running when the batch wait expired.

ForbiddenError

Bases: YouSleepClientError

Access forbidden (403 Forbidden).

InsufficientCreditsError

Bases: YouSleepClientError

Not enough credits for the requested operation (402 Payment Required).

NotFoundError

Bases: YouSleepClientError

Resource not found (404 Not Found).

QuotaExceededError

Bases: YouSleepClientError

A usage quota was exceeded (projects, studies, analyses, analysis hours, ...).

The server reports quota violations with HTTP 429 like rate limiting, but a quota error will not clear by waiting — the client raises this immediately without retrying. Check your limits via client.user.usage_limits() and current usage via client.user.usage_detailed().

RateLimitError

Bases: YouSleepClientError

Rate limit exceeded (429 Too Many Requests).

__init__(message, retry_after=None, **kwargs)

Initialize rate limit error.

Parameters:

Name Type Description Default
message str

Error message

required
retry_after int | None

Seconds until retry is allowed

None
**kwargs Any

Additional arguments passed to parent

{}

ServerError

Bases: YouSleepClientError

Server error (5xx status codes).

ValidationError

Bases: YouSleepClientError

Request validation failed (422 Unprocessable Entity).

__init__(message, errors=None, **kwargs)

Initialize validation error.

Parameters:

Name Type Description Default
message str

Error message

required
errors dict[str, Any] | None

Validation error details

None
**kwargs Any

Additional arguments passed to parent

{}

YouSleepClientError

Bases: Exception

Base exception for all client errors.

__init__(message, status_code=None, response=None, code=None)

Initialize the exception.

Parameters:

Name Type Description Default
message str

Error message

required
status_code int | None

HTTP status code if applicable

None
response Any

Raw response object if available

None
code str | None

Machine-readable API error code (ErrorCode value), if the server provided one

None