# Integrations and API

Connect your app to external systems securely and predictably.

Use this page as **decision guide + checklist**. Then, detail per case.

{% hint style="info" %}
Integrations almost always touch authentication and governance. Combine with [Runtime Settings](https://app.gitbook.com/s/XnYvLewhXbdSQIvAlbqN/documentacao/configuracoes-do-runtime).
{% endhint %}

### Quick decisions (before implementing)

1. **Direction:** Inbound (incoming) or Outbound (outgoing)?
2. **Mode:** synchronous (API) or asynchronous (events/webhook/queue)?
3. **Frequency:** real-time, near real-time, or batch?
4. **Contract:** do you control both sides (better) or is it a “third-party API”?
5. **Reliability:** need retries, reprocessing, idempotency?

### Minimum checklist (production)

* **Environments:** endpoints and credentials per Dev/Staging/Prod.
* **Authorization:** least privilege (minimal scopes/roles).
* **Secret rotation:** with date and owner.
* **Observability:** logs + correlation (e.g.: `requestId`, `eventId`).
* **Failure handling:** retry with backoff + dead-letter/reprocess.
* **LGPD:** avoid leaking PII in logs and payloads.

### API Authentication (OAuth2/OIDC, tokens)

Choose a standard and document it. Avoid “fixed token” without rotation.

#### Common options

* **OAuth2 Client Credentials:** good for system-to-system integration.
* **OAuth2 Authorization Code (with PKCE):** good when there's a user.
* **OIDC (ID token):** for identity; does not replace API authorization.
* **API keys / personal tokens:** only if rotation and scope exist.

#### Practical rules

* Validate **audience**, **issuer** and token expiration.
* Separate “who authenticated” from “what they can do” (claims vs roles).
* Standardize error response:
  * `401`: not authenticated / invalid/expired token.
  * `403`: authenticated, but without permission.

{% hint style="warning" %}
If you use corporate SSO, validate claims and group mapping. See [SSO and login](https://app.gitbook.com/s/XnYvLewhXbdSQIvAlbqN/solucao-de-problemas/sso-e-login).
{% endhint %}

### Rate limits and quotas

Rate limit is part of the contract. Document limit and retry behavior.

#### Client best practices

* Treat `429 Too Many Requests` as expected.
* Respect `Retry-After` when present.
* Use **exponential backoff** with jitter.
* Controlled parallelism. Avoid “fan-out” without limit.

#### How to design limits (server side)

* Limit by **tenant** + by **credential** (service account).
* Differentiate **burst** vs **sustained**.
* Protect expensive endpoints (search, reports, exports).

### Webhooks

Webhooks are the simplest way to be “event-driven” when you don't control queues.

#### Webhook checklist (sender)

* Versioned payload (`schemaVersion`).
* `eventId` single + `occurredAt`.
* Automatic retry with backoff.
* Payload signature (e.g.: HMAC) + secret rotation.

#### Webhook checklist (receiver)

* Respond `2xx` quickly. Process asynchronously.
* Implement **idempotency** by `eventId`.
* Log: status, attempts, last error, processing time.
* Have a button/route to **reprocess** for events with errors.

<details>

<summary>Specification template (copy and paste)</summary>

```
Webhook: {{name}}

Events:
- {{event1}}
- {{event2}}

Contract:
- eventId: string (unique)
- occurredAt: ISO-8601
- type: string (event name)
- payload: object (versioned schema)

Reliability:
- Retry: yes, with backoff
- Idempotency: by eventId
- Receiver timeout: {{N}}s

Security:
- Signature: HMAC-SHA256
- Signature header: {{headerName}}
- Secret rotation: every {{N}} days
```

</details>

### Connectors (ERP/CRM/…)

A connector is an integration package with:

* Authentication + credential renewal.
* Object mapping (e.g.: `Customer` ↔ `Account`).
* Synchronization (push, pull, or both).
* Error handling and reprocessing.

#### Sync strategies (choose 1)

* **Pull (polling):** simple, but increases cost and latency.
* **Push (webhook/event):** better for real-time.
* **Hybrid:** webhook + daily reconcile (reduces “drift”).

{% hint style="info" %}
If you need to “integrate fast”, start with hybrid. Webhooks fail. Reconciliation saves.
{% endhint %}

### Integration with database / data access

Direct integration via database is powerful, but risky.

#### Guardrails

* Prefer **read** (views/read replica) instead of direct write.
* Define schema owner. Avoid “app writing to ERP schema”.
* Do not couple to volatile internal tables. Prefer stable views.
* Log slow queries. Create indexes carefully.

### How to request this in Madrix (prompts)

If you will generate/adjust integration via Chat AI, provide testable requirements.

{% hint style="success" %}
For a ready prompt for integration with log + reprocess, see the block **Integrations** in [Quick prompts](https://app.gitbook.com/s/XnYvLewhXbdSQIvAlbqN/tutoriais-praticos/2.-prompts-rapidos).
{% endhint %}

<details>

<summary>Base prompt — integration via webhook (copy and paste)</summary>

```
Implement a webhook for the event {{event}}.

Requirements:
- Endpoint configurable per environment (Dev/Staging/Prod).
- Log payload, status, attempts and errors.
- Idempotency by eventId.
- Allow reprocessing events with errors (Admin only).
- Do not expose sensitive data in logs.
```

</details>

### Quick troubleshooting

* **401/403 in integration:** token expired? scopes/roles correct?
* **429:** high parallelism? missing backoff? is there batch?
* **Webhook duplicating:** missing idempotency by `eventId`.
* **“Slow” integration:** external call blocking main request? See [Performance and slowness](https://app.gitbook.com/s/XnYvLewhXbdSQIvAlbqN/solucao-de-problemas/performance-e-lentidao).
