# Building on the Demeter API (Third-Party Integration)

This guide is for **third-party developers** building an application or
integration **on top of** Demeter's REST API. (If instead you're connecting a
commercial device/hub _into_ Demeter, see the
[integration guide](../integrations/third-party-integrations.md).)

## Start from the spec

The API is OpenAPI 3.1 and self-documenting:

- **Explore:** `GET /docs` (Swagger UI).
- **Codegen:** `GET /docs/json` — feed the spec to `openapi-typescript`,
  `openapi-generator`, or similar to generate a typed client.

All resource endpoints are under `/v1`; see the
[API reference](../api/README.md).

## Authenticate

Two credential types:

| Use case                                 | Credential                                                                |
| ---------------------------------------- | ------------------------------------------------------------------------- |
| Acting as a user (web/mobile-style)      | **Bearer JWT** from `POST /v1/auth/login` (refresh via the rotation flow) |
| Machine-to-machine / backend integration | **API key** (scoped permissions, `Authorization` header)                  |

Request only the permissions you need — API keys are scoped, stored hashed, and
revocable (see
[ADR-0004](../architecture/adr/0004-jwt-refresh-rotation-auth.md)).

## Be a good client

- **Versioning:** target `/v1`; the spec's `info.version` tracks releases (see
  [changelog & versioning](changelog-versioning.md)).
- **Refresh handling:** access tokens are short-lived. Store the newest refresh
  token (rotation issues a fresh one each use); retry a `401` once after
  refreshing. A reused/revoked refresh token revokes the whole family — treat
  that as "re-authenticate".
- **Rate limits:** expect `429` under burst; honour `Retry-After` and back off.
  Don't disable limits — design for them.
- **Validation:** requests are Zod-validated; a `400` means fix the payload, a
  `404` on a malformed id means the id wasn't a valid UUID.

## Typical flows

- **Read a user's gardens:** `GET /v1/gardens` (Bearer).
- **Ingest external readings:** `POST /v1/sensors/:id/readings` (API key) —
  match the `NormalizedReading` shape.
- **Pull harvest analytics:** `GET /v1/harvests` + `/v1/analytics` endpoints.

## Support

The OpenAPI spec is the contract; the [data-models doc](../data-models.md)
explains request/response shapes and the row↔DTO conventions.
