API routes
Answer /api/<app>/<path> with your own status, headers and body, for webhooks, protocols and streamed files.
An RPC answers in Cardinal's {"data": ...} envelope. When a caller expects another shape, such as a payment provider's webhook or an MCP client, use an API route. It answers every HTTP method at /api/<app>/<path> on sites that have the app installed.
Declare routes
api_routes: [
{"twilio-voice", Crm.Api.TwilioVoice},
{"twilio-status", Crm.Api.TwilioStatus},
{"recording", Crm.Api.Recording}
]The path is one URL segment. Eden serves its MCP server the same way, with {"mcp", Eden.Api.Mcp} and {"mcp-events", Eden.Api.McpEvents}.
Write one
A module implements Cardinal.ApiRoute with handle(ctx, request) and returns {status, headers, body}:
defmodule Library.Api.Ping do
@behaviour Cardinal.ApiRoute
@impl true
def handle(%{auth: :guest}, _req), do: {403, [{"content-type", "text/plain"}], "Log in first"}
def handle(_ctx, %{method: "GET"}), do: {200, [{"content-type", "application/json"}], ~s({"ok":true})}
def handle(_ctx, _req), do: {405, [{"allow", "GET"}], ""}
endWith {"ping", Library.Api.Ping} in api_routes, this answers GET /api/library/ping.
| Request key | Holds |
|---|---|
method | Upper case, such as "POST" |
host | The request's host |
headers | Lower-case {name, value} pairs |
query | The decoded query string |
body | The decoded JSON body, nil when not JSON |
raw_body | The exact bytes received, for checking a webhook's signature |
What the platform does first
Finds the site and identifies the caller: a session, or an API key as token, Basic or Bearer.
Runs the CSRF check on a session's unsafe request, and the 8 MB body limit.
Calls handle/2 outside any transaction. Open one with Cardinal.DB.transaction/2 when you need it.
A Guest reaches the module too. Refuse one yourself when the route needs a user. A Guest's POST may be a form (application/x-www-form-urlencoded), as webhooks send. It arrives only in raw_body, so check the caller's signature before you trust it.
Rate limits
case Cardinal.ApiRoute.limit(ctx, "recording", {120, 60}) do
:ok -> serve(ctx, req)
{:error, {:rate_limited, retry_after}} -> {429, [{"retry-after", to_string(retry_after)}], ""}
endThe count is per user, or per client address for a Guest, and holds across nodes.
Streaming
Return {:stream, fun} to send the body in pieces. The platform calls fun with send. Call send.({:head, status, headers}) once, then send.(iodata) per piece. Each call returns :ok, or :halt once the client has gone.
CRM's recording route relays a provider's audio this way, with Cardinal.HTTP.stream/7 and head: true, so a browser's Range request gets a 206 and only one piece is in memory. A fun that returns without sending the head answers 502.