# The Integration API

`/api/v1`, in the Platform module (`Platform\Api`), with resources declared by the modules that own them.

## Declaring a resource

Implement `Platform\Contracts\ApiResource` (with `use Platform\Data\ApiResourceDefaults` for the usual answers) in
your module's `Api/` folder and tag it in the module's `register()`: `$this->app->tag([MyResource::class],
ApiResource::TAG)`. The contract and the trait keep the module boundary: a module reaches Platform only through its
Contracts and Data. It declares:

- `key()` (snake_case: the scope `{key}:read|write` and the docs key) and `group()` (the module's lang file);
- `fields()`: `ApiField::make($name, $type)` (`Platform\Data\ApiField`) with `->writable($required)`, `->nullable()`, `->max()`, `->enum()`,
  `->example()`, `->rules()`; they give the write validation and the OpenAPI schema;
- `query()`, `filters()` + `filter()`, `transform()` (an explicit array; moments through `self::moment()` in UTC);
- `operations()` (`list`, `show`, `create`, `update`, `delete`) and `actions()` (`POST /{path}/{id}/{action}`),
  carried out through the module's own Actions with `$context->actorId()` (`Platform\Data\ApiContext`) as the user.

Texts: `packages/core/lang/{ro,en}/{group}.php` › `api.{key}.title|description|fields.*|filters.*|actions.*|actions_fields.*`.
`Platform\Api\Registry` collects the tagged resources; `ApiDocs` builds `/api/openapi.json` (3.1) and
`/api/postman.json` (v2.1) from them. Nothing is written by hand.

## Requests

`Http\Controllers\Api\ResourceController` serves every resource: list (`page`, `per_page` ≤ 100, `sort` on
`id|created_at|updated_at` with `-`, `updated_since`) → `{data, meta, links}`; show → `{data}`; create → 201;
update (only the fields sent); delete → 204 or 409 `in_use`. A body with unknown or read-only fields is refused (422
`body`). Errors are `{"error": code, "message": text}`; validation errors are Laravel's 422.

Middleware, in order: `LogApiRequest` (in `terminate()`, in its own savepoint; method, path, status, duration, an
error's message; never bodies), `throttle:api-ip` (300/min per address), `AuthenticateApiKey` (key, active, not
expired, allowed address, holder still holds `api.manage` → `ApiContext`), `throttle:api-key` (120/min per key).

Keys (`api_keys`): `ss_<id>_<secret>`, only `sha256(secret)` stored; `ApiKey::generate()`, `rotate()`, `resolve()`.
The request log is pruned after 30 days by `platform:retention`.

Tests: `tests/Feature/Api/IntegrationApiTest.php`.

## Outgoing webhooks

`Platform\Contracts\Webhooks`: a module declares its events in `boot()` (`declare($event, $labelKey, $permission)`)
and sends them from a listener on its own domain events (`send($event, $data)`, ids and a few fields). The
singleton `Webhooks\DatabaseWebhooks` writes one `webhook_deliveries` row per active endpoint that wants the event
and whose registrar still holds `api.manage` and the event's permission, then queues `DeliverWebhook` after commit.
`Webhooks\Sender` signs (`X-SyncShop-Signature: t=…,v1=hex(HMAC-SHA256(secret, "t.body"))`), refuses addresses
that are not public HTTPS (`Webhooks\SafeUrl`, checked on save and before each send; no redirects followed, 10 s),
and schedules retries on `Sender::BACKOFF`; `webhooks:retry` runs them every minute. Senders today: Orders,
Inventory (`StockLow`, new), Customers (`CustomerRegistered`, new), Fulfilment, Subscriptions.

Tests: `tests/Feature/Api/WebhooksTest.php`.

## Bulk updates

`Platform\Contracts\ApiBulkHandler` (tag `api-bulk`): `kind()` (the URL segment), `scope()`, `permission()`,
per-row `rules()`, `apply($row, $userId)` and an `example()` row for the reference. `POST /api/v1/bulk/{kind}`
(≤ 5 000 rows) stores an `api_bulk_jobs` row and queues `Api\RunBulkJob`, which validates and applies each row on its
own, keeps the first 500 row errors by index, and drops the rows when done; `GET /api/v1/bulk/{id}` answers only the
key that started it. Handlers today: Inventory `stock` (CountStock per row), Catalog `prices` (the variant's price
through its money cast, so the price history records it).

A resource's own `rules()` are added to its fields' rules; a `required…` one also drops the field's `sometimes`, so
it runs when the field is absent (e.g. a voucher's `amount` is `required_if:kind,fixed`).

Next: the Storefront API.
