SDK

Готовые клиенты для популярных языков. Один файл, без внешних зависимостей, компактные ~80 строк. Скопируйте код ниже и используйте сразу.

Статус публикации: SDK сейчас распространяется только через эту страницу. Публикация на npm и PyPI запланирована после первой волны adoption. Если хотите получать уведомления о релизе — напишите на mir@taliora.ru.

JavaScript / TypeScript

Поддерживает Node.js 18+, Bun, Deno, браузеры. Используется встроенный fetch — никаких внешних зависимостей.

Установка

Скопируйте код ниже в файл taliora-client.ts в вашем проекте.

taliora-client.ts
/**
 * TalioraClient — клиент Taliora Open Numerology API.
 *
 * Лицензия: MIT (код), CC-BY 4.0 (данные).
 * Документация: https://taliora.ru/docs
 */

export interface ArcanaPosition {
  arcana: number;
  name: string;
  keyword: string;
  emoji: string;
}

export interface Matrix {
  personal: ArcanaPosition; social: ArcanaPosition;
  soul: ArcanaPosition;     body: ArcanaPosition;
  spirit: ArcanaPosition;   center: ArcanaPosition;
  talents: ArcanaPosition;  karma: ArcanaPosition;
  money: ArcanaPosition;    relationships: ArcanaPosition;
  destiny: ArcanaPosition;  purpose: ArcanaPosition;
}

export interface MatrixResponse {
  input: { day: number; month: number; year: number };
  matrix: Matrix;
  source_url: string;
  details_url: string;
  license: string;
  attribution: string;
  attribution_html: string;
  api_version: string;
}

export type LifePathNumber = 1|2|3|4|5|6|7|8|9|11|22|33;

export class TalioraError extends Error {
  constructor(public status: number, public body: unknown) {
    super(`Taliora API HTTP ${status}`);
    this.name = "TalioraError";
  }
}

export class TalioraClient {
  private baseUrl: string;
  private timeoutMs: number;

  constructor(opts: { baseUrl?: string; timeoutMs?: number } = {}) {
    this.baseUrl = (opts.baseUrl ?? "https://taliora.ru/api/public").replace(/\/$/, "");
    this.timeoutMs = opts.timeoutMs ?? 10_000;
  }

  async getMatrix(day: number, month: number, year: number): Promise<MatrixResponse> {
    return this.request<MatrixResponse>(`/matrix/${day}/${month}/${year}`);
  }

  async getLifePath(n: LifePathNumber | number): Promise<unknown> {
    return this.request(`/life-path/${n}`);
  }

  async listLifePaths(): Promise<unknown[]> {
    return this.request(`/life-path`);
  }

  private async request<T>(path: string): Promise<T> {
    const res = await fetch(`${this.baseUrl}${path}`, {
      headers: { Accept: "application/json" },
      signal: AbortSignal.timeout(this.timeoutMs),
    });
    if (!res.ok) {
      const body = await res.json().catch(() => null);
      throw new TalioraError(res.status, body);
    }
    return res.json();
  }
}

Использование

example.ts
import { TalioraClient } from "./taliora-client";

const client = new TalioraClient();

// Матрица судьбы
const matrix = await client.getMatrix(15, 3, 1990);
console.log(matrix.matrix.center.name); // "Колесо Фортуны"
console.log(matrix.matrix.money.emoji); // "⚡"

// Число жизненного пути
const lp = await client.getLifePath(7);
console.log(lp);

// Список всех чисел
const all = await client.listLifePaths();
console.log(all.length); // 12

Если предпочитаете чистый JavaScript без TypeScript — удалите типы из исходника (всё что после interface, type, : string, и т.п.), останется рабочий ES-модуль ~30 строк.

Python

Python 3.8+. Без зависимостей — только стандартная библиотека urllib.

Установка

Скопируйте код ниже в файл taliora_client.py в вашем проекте.

taliora_client.py
"""
TalioraClient — клиент Taliora Open Numerology API.

Лицензия: MIT (код), CC-BY 4.0 (данные).
Документация: https://taliora.ru/docs
"""
import json
import urllib.error
import urllib.request
from typing import Any, Dict, List


class TalioraError(Exception):
    def __init__(self, message: str, status: int, body: Any):
        super().__init__(message)
        self.status = status
        self.body = body


class TalioraClient:
    def __init__(
        self,
        base_url: str = "https://taliora.ru/api/public",
        timeout: float = 10.0,
        user_agent: str = "taliora-python/1.0",
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.user_agent = user_agent

    def get_matrix(self, day: int, month: int, year: int) -> Dict[str, Any]:
        return self._request(f"/matrix/{int(day)}/{int(month)}/{int(year)}")

    def list_life_paths(self) -> List[Dict[str, Any]]:
        return self._request("/life-path")

    def get_life_path(self, number: int) -> Dict[str, Any]:
        return self._request(f"/life-path/{int(number)}")

    def _request(self, path: str) -> Any:
        req = urllib.request.Request(
            f"{self.base_url}{path}",
            headers={"Accept": "application/json", "User-Agent": self.user_agent},
            method="GET",
        )
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as r:
                return json.loads(r.read().decode("utf-8"))
        except urllib.error.HTTPError as e:
            try:
                body = json.loads(e.read().decode("utf-8"))
            except Exception:
                body = None
            raise TalioraError(f"Taliora API HTTP {e.code}", e.code, body) from None
        except urllib.error.URLError as e:
            raise TalioraError(f"Network error: {e.reason}", 0, None) from None


# Использование:
#   from taliora_client import TalioraClient
#   client = TalioraClient()
#   matrix = client.get_matrix(day=15, month=3, year=1990)
#   print(matrix["matrix"]["center"]["name"])  # "Колесо Фортуны"

Использование

example.py
from taliora_client import TalioraClient

client = TalioraClient()

# Матрица судьбы
matrix = client.get_matrix(day=15, month=3, year=1990)
print(matrix["matrix"]["center"]["name"])  # "Колесо Фортуны"
print(matrix["matrix"]["money"]["emoji"])  # "⚡"

# Число жизненного пути
lp = client.get_life_path(7)
print(lp["archetype"])  # "Мудрец"

Async-вариант

Если вам нужен async-клиент — соберите аналог с использованием aiohttp или httpx.AsyncClient по той же сигнатуре. Логика идентична синхронной версии, отличие только в await.

Без SDK

API настолько простой, что SDK не обязателен. Минимальный вызов в любом языке:

curl https://taliora.ru/api/public/matrix/15/3/1990

Другие языки

Можно сгенерировать клиент на 50+ языках из OpenAPI 3.0 спецификации через openapi-generator (Go, Java, C#, Rust, Swift, Kotlin, Ruby и другие).

Обратная связь

Нашли баг, хотите новый язык или async-вариант — пишите на mir@taliora.ru. Open source-релиз с GitHub-репозиторием — после публикации на npm/PyPI.