---
title: "Build a Python Client"
description: "Create a small Python client for Y2 JSON reads, writes, errors, and pagination"
canonical: https://y2.dev/docs/sdks/python/
---

# Build a Python Client

Create a small Python client for Y2 JSON reads, writes, errors, and pagination

Use Python 3.11 or later and the standard library to call Y2. Before you begin, [create a key](https://y2.dev/docs/api/create-key) with `news:read`.

Keep credentials out of notebooks and source files

Load `Y2_API_KEY` from the environment or a secret manager. Notebook output, exception dumps, and committed `.env` files can leak credentials as easily as application logs.

## Configure the environment

The examples use Python 3.11 or newer and only the standard library:

```
export Y2_API_KEY="y2_..."
python --version
```

New keys require a Pro or Elite workspace and the scopes needed by the operations you call.

## Make a first request

Save this complete example as `first_request.py`:

first\_request.py

```
import json
import os
from urllib.request import Request, urlopen

request = Request(
    "https://api.y2.dev/api/v1/news?limit=1",
    headers={
        "Authorization": f"Bearer {os.environ['Y2_API_KEY']}",
        "Accept": "application/json",
    },
)
with urlopen(request, timeout=30) as response:
    print(response.status)
    page = json.load(response)

for item in page["data"]:
    print(item["title"], item["links"]["canonical"])
```

Run `python first_request.py` with `Y2_API_KEY` set. Expect `200`, followed by up to one title and source URL. An empty collection prints only `200`. For an HTTP error, see [API errors](https://y2.dev/docs/api/responses#errors).

## Create a reusable JSON transport

y2\_client.py

```
from __future__ import annotations

import json
import os
from dataclasses import dataclass
from typing import Any, Mapping, TypeVar, cast
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

T = TypeVar("T")
API_ORIGIN = "https://api.y2.dev"
API_V1 = f"{API_ORIGIN}/api/v1"

class Y2ApiError(Exception):
    def __init__(
        self,
        status: int,
        problem: dict[str, Any] | None,
        retry_after: str | None,
        request_id: str | None,
    ) -> None:
        detail = problem.get("detail") if problem else None
        super().__init__(detail or f"Y2 request failed with HTTP {status}")
        self.status = status
        self.problem = problem
        self.retry_after = retry_after
        self.request_id = request_id

@dataclass(frozen=True)
class Y2Client:
    api_key: str
    timeout_seconds: float = 30.0

    @classmethod
    def from_env(cls) -> Y2Client:
        api_key = os.environ.get("Y2_API_KEY")
        if not api_key:
            raise RuntimeError("Y2_API_KEY is required")
        return cls(api_key=api_key)

    def request_json(
        self,
        method: str,
        path_or_url: str,
        *,
        query: Mapping[str, str | int | float | bool | None] | None = None,
        body: Mapping[str, Any] | None = None,
        headers: Mapping[str, str] | None = None,
    ) -> T:
        if path_or_url.startswith("https://"):
            url = path_or_url
        elif path_or_url.startswith("/api/"):
            url = f"{API_ORIGIN}{path_or_url}"
        else:
            url = f"{API_V1}{path_or_url}"

        params = {
            key: str(value).lower() if isinstance(value, bool) else value
            for key, value in (query or {}).items()
            if value is not None
        }
        if params:
            separator = "&" if "?" in url else "?"
            url = f"{url}{separator}{urlencode(params)}"

        request_headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Accept": "application/json",
            **(headers or {}),
        }
        data = None
        if body is not None:
            request_headers.setdefault("Content-Type", "application/json")
            data = json.dumps(body, separators=(",", ":")).encode("utf-8")

        request = Request(url, data=data, headers=request_headers, method=method)
        try:
            with urlopen(request, timeout=self.timeout_seconds) as response:
                raw = response.read()
                if response.status == 204 or not raw:
                    return cast(T, None)
                return cast(T, json.loads(raw))
        except HTTPError as error:
            raw = error.read()
            problem = None
            if raw:
                try:
                    decoded = json.loads(raw)
                    if isinstance(decoded, dict):
                        problem = decoded
                except json.JSONDecodeError:
                    pass
            raise Y2ApiError(
                error.code,
                problem,
                error.headers.get("Retry-After"),
                error.headers.get("X-Request-Id"),
            ) from error
```

This helper handles JSON and `204 No Content`. Use separate readers for text, NDJSON, audio redirects, and SSE.

## Read news items

news.py

```
from typing import Any, TypedDict

from y2_client import Y2Client

class NewsPage(TypedDict):
    data: list[dict[str, Any]]
    meta: dict[str, Any]
    links: dict[str, str | None]

client = Y2Client.from_env()
page: NewsPage = client.request_json(
    "GET",
    "/news",
    query={"topics": "markets,macro", "limit": 10},
)

for item in page["data"]:
    print(item["title"], item["links"]["canonical"])
```

Use `GET /news/feeds` to discover topics. Items contain `title`, `summary`, and a nested `sentiment` object. Read `sentiment.label` and `sentiment.value`.

## Create a profile

Use a key with `profiles:write`.

profiles.py

```
from typing import Any

from y2_client import Y2Client

client = Y2Client.from_env()

created: dict[str, Any] = client.request_json(
    "POST",
    "/profiles",
    headers={"Idempotency-Key": "supplier-risk-2026-07-21"},
    body={
        "name": "Critical Supplier Risk",
        "topic": "Monitor disruption affecting strategic semiconductor suppliers.",
        "frequency": "daily",
        "scheduleTimeOfDay": "08:00",
        "isCommunity": False,
    },
)

profile_id = created["data"]["id"]
print(profile_id)  # prf_...
```

Creation returns the profile in `data`. Use `GET /profiles` to find the associated `sub_...` subscription ID for delivery changes.

Use `PATCH /profiles/{profileId}` for partial changes. `PUT` replaces mutable state and resets omitted optional values. Extend this helper to retain `ETag` headers if you need `If-Match` concurrency protection.

## Follow report pagination

Use a key with `reports:read`. Replace the example profile ID with an accessible profile ID.

reports.py

```
from collections.abc import Iterator
from typing import Any

from y2_client import Y2Client

def reports_for_profile(
    client: Y2Client,
    profile_id: str,
) -> Iterator[dict[str, Any]]:
    next_url: str | None = "/reports"
    first = True

    while next_url:
        page: dict[str, Any] = client.request_json(
            "GET",
            next_url,
            query={"profileId": profile_id, "limit": 20} if first else None,
        )
        yield from page["data"]
        next_url = page["links"]["next"]
        first = False

client = Y2Client.from_env()
for report in reports_for_profile(client, "prf_0123456789abcdef01234567"):
    print(report["id"], report["summary"])
```

Treat `links.next` and its cursor as opaque. Do not decode, edit, or combine a continuation link with different filters.

## Run independent reads concurrently

The standard-library transport is synchronous. For a small job, run independent calls in worker threads without sharing mutable client state:

concurrent\_reads.py

```
import asyncio

from y2_client import Y2Client

async def main() -> None:
    client = Y2Client.from_env()
    news, feeds = await asyncio.gather(
        asyncio.to_thread(
            client.request_json,
            "GET",
            "/news?topics=markets&limit=10",
        ),
        asyncio.to_thread(client.request_json, "GET", "/news/feeds"),
    )
    print(len(news["data"]), len(feeds["data"]))

asyncio.run(main())
```

For more concurrent requests, use an async HTTP client with connection pooling. Keep the same authentication, timeout, error, pagination, and response-format rules.

## Handle Problem Details

errors.py

```
from y2_client import Y2ApiError, Y2Client

client = Y2Client.from_env()

try:
    client.request_json("GET", "/reports/not-a-report-id")
except Y2ApiError as error:
    code = error.problem.get("code") if error.problem else "UNKNOWN"
    print(error.status, code, error.request_id)

    if error.status == 429:
        print("Retry after", error.retry_after)
```

Retry only safe reads or writes protected by an idempotency key. A `404` on tenant-owned resources can intentionally avoid revealing whether another tenant owns the ID.

## Call Intel v2 with the correct base

Intel paths include `/api/v2` and use `https://api.y2.dev` as the server. Use a key with an accepted Intel scope:

```
from y2_client import Y2Client

client = Y2Client.from_env()
incidents = client.request_json(
    "GET",
    "https://api.y2.dev/api/v2/incidents",
    query={"limit": 20},
)
```

Do not prepend `https://api.y2.dev/api/v1` to an Intel v2 path.

## Evaluate a generated Python client

If you generate models and operation methods from OpenAPI, verify that the result:

- honors operation-level server overrides.
- represents nullable and optional fields separately.
- exposes `application/problem+json` rather than replacing it with generic exceptions.
- preserves response headers for rate limits, ETags, request IDs, and x402.
- handles `204` and `302` without trying to decode JSON.
- provides explicit streaming APIs for NDJSON and Agent Y2 SSE.

Compare a generated package with the current endpoint reference before using it. Package releases can differ from the API contract.

[OpenAPI contract](https://y2.dev/docs/api/openapi)

[Endpoint reference](https://y2.dev/docs/api/reference)

[Profiles API](https://y2.dev/docs/api/profiles)

[Reports API](https://y2.dev/docs/api/reports)
