API
API: обзор и стандарты
This page holds the contract standards. Every endpoint that exists today, with its methods, request bodies, status codes and schemas, is in the endpoint reference — generated from the served OpenAPI 3.1 document, so it cannot describe a contract the runtime does not have.
Current surface: eight operations across four areas. Three read-only demo resources carry synthetic payloads and no live customer telemetry; the runtime probes expose a state word and nothing else; the account export and the two Telegram operations are the real, authenticated surface.
| Area | Operations |
|---|---|
| Platform demo | GET /api/platform/templates, GET /api/platform/projects, GET /api/platform/status |
| Operations | GET /api/health, GET /api/openapi |
| Account | GET /api/account/export |
| Telegram | POST /api/telegram/auth, POST /api/telegram/webhook |
The versioned management API under /api/v1 remains planned and is deliberately
absent from the published contract.
Where to read it
| Surface | Local URL | Dev URL |
|---|---|---|
| Human-readable reference | http://localhost:3000/api-docs |
https://dev.feelcouch.tech/api-docs |
| OpenAPI JSON | http://localhost:3000/api/openapi |
https://dev.feelcouch.tech/api/openapi |
| This handbook | http://127.0.0.1:8000/api/endpoints/ |
see Documentation access |
The human-readable reference is rendered by Next.js without remote assets.
npm run check:docs fails the build when the handbook page and the served
document disagree; npm run docs:api regenerates the page.
Базовые адреса
| Назначение | Планируемый адрес |
|---|---|
| REST API | https://dev.feelcouch.tech/api/v1 |
| OpenAPI JSON | https://dev.feelcouch.tech/api/openapi |
| Interactive reference | https://dev.feelcouch.tech/api-docs |
| Webhooks | URL клиента, зарегистрированный в Console |
Production base URL определяется отдельно после разделения пилота и платформы.
Принципы контракта
- OpenAPI 3.1 является проверяемым контрактом, а не документацией задним числом;
- breaking changes требуют новой major version;
- additive fields не меняют смысл существующих полей;
- timestamps используют RFC 3339 UTC;
- IDs непрозрачны и не кодируют персональные данные;
- money передаётся integer minor units или decimal string + currency/asset;
- list endpoints имеют cursor pagination;
- каждый write принимает/возвращает request ID, а retryable create —
Idempotency-Key; - errors имеют стабильный machine code и безопасное human message.
Accept-Languageподдерживаетruиen; локализация никогда не меняет machine codes, field names или enum values.
Аутентификация
Private owner Console на dev.feelcouch.tech/admin использует защищённую session cookie и CSRF/origin controls. Server-to-server API использует scoped service token; token привязан к tenant и окружению. Telegram init data не заменяет service authentication.
POST /api/v1/projects
Authorization: Bearer fc_test_...
Idempotency-Key: 01J...
Content-Type: application/json
X-Request-Id: 01J...
Tokens показываются один раз, хранятся hashed/encrypted согласно типу и могут быть отозваны. Scope задаёт разрешённые ресурсы и действия.
Error envelope
{
"error": {
"code": "project_slug_conflict",
"message": "Этот адрес уже используется.",
"request_id": "01J6QX...",
"details": []
}
}
Stack traces, DB names, provider secrets и персональные данные не возвращаются.
Locale contract
- request использует
Accept-Language: ruилиen; - response может вернуть
Content-Languageс фактически выбранной locale; - fallback: requested → tenant default → platform English;
- даты остаются RFC 3339 UTC, форматируются только в UI;
- API не принимает переведённые enum values;
- localized content resource содержит stable key, locale, catalog version и channel variant;
- OpenAPI examples включают RU/EN error messages с одним и тем же
code.
Планируемые endpoints управления catalog доступны только owner/admin scope. Publish выполняется idempotently и создаёт immutable catalog version; UI, bot menu и notifications читают одну опубликованную версию.
Планируемые ресурсы
/templates— каталог доступных templates;/projects— lifecycle клиентского проекта;/projects/{id}/domains— DNS/TLS verification;/projects/{id}/telegram— bot connection state без возврата token;/projects/{id}/deployments— запуск и состояние deploy;/projects/{id}/health— приватная operational projection;/invoices— только после payment/legal approval;/events— audit и integration events с ограниченным retention./projects/{id}/localization— catalogs, completeness, preview и publish.
Webhooks
- HMAC signature над raw body + timestamp;
- replay window;
- уникальный event ID;
- at-least-once delivery, поэтому consumer обязан быть idempotent;
- exponential backoff, ограничение попыток и ручной redrive;
- secret rotation с временным overlap двух ключей;
- endpoint verification до включения событий.
X-Feelcouch-Event: deployment.ready
X-Feelcouch-Delivery: evt_01J...
X-Feelcouch-Timestamp: 1788200000
X-Feelcouch-Signature: v1=...
Rate limits
Limits задаются по tenant, token, endpoint class и risk level. Ответ 429 возвращает Retry-After. Security endpoints имеют отдельные более строгие limits; webhook retries не обходят tenant quotas бесконтрольно.
OpenAPI delivery gate
- schema проходит lint;
- examples валидируются по schema;
- generated client используется хотя бы в contract test;
- auth scopes присутствуют у каждой operation;
- sensitive fields отмечены
writeOnly/readOnly; - undocumented production endpoint не допускается в
/api/v1; - changelog и deprecation window опубликованы.
Эти ворота относятся к будущему /api/v1. Текущая спецификация уже опубликована и покрывает ровно те восемь операций, которые обслуживает runtime: она отдаётся по GET /api/openapi, отображается на /api-docs и разворачивается в endpoint reference. Ни одна операция не документируется авансом: npm run check:docs в CI роняет сборку, если справочник и отдаваемый документ разошлись, а тест контракта обходит app/api и требует совпадения в обе стороны.