
Documentation
API and outgoing webhooks
Connect your system to Kaptia: create, read, change and move leads with an account key, and get a signed notice for every new lead, stage change, sale and contract. Here you have the key, the routes, the errors, the signature and examples in cURL, JavaScript, PHP and Python.
- The owner creates one key per system under More, Integrations, API, and your server creates, reads, changes and moves leads with it.
- The same phone or email never becomes another lead, and the Idempotency-Key lets you repeat a request safely.
- Outgoing webhooks notify your system, with a signature, when a lead is created, changes stage or data, and on every sale and contract.
Overview
The Kaptia API lets your system talk to the CRM: create and find leads, change their data, move them between stages and read the account's stages, tags and fields. Outgoing webhooks go the other way: Kaptia notifies your system, with a signed POST, when a lead is created, changes stage or data, when a sale is recorded and when a contract is signed.
Base address
https://usekaptia.com/api/v1/publica- REST with JSON in UTF-8: send
Content-Type: application/jsonwhen there is a body, and every response comes back as JSON. - Every call carries the account key in the
Authorizationheader (see Authentication). - Ids are uuids, dates come in ISO 8601 UTC (
2026-11-26T14:03:12.481Z) and money comes in cents. - Responses are sent with
Cache-Control: no-store.
The routes
| Route | What it does | Key |
|---|---|---|
GET /leads | Lists leads, with filters and pages. | Read only |
GET /leads/{id} | One lead. | Read only |
POST /leads | Creates the lead, or returns the one that already exists. | Read and write |
PATCH /leads/{id} | Changes name, notes, stage, tags and fields. | Read and write |
POST /leads/{id}/etapa | Moves the stage. | Read and write |
GET /etapas | The pipeline stages. | Read only |
GET /etiquetas | The account's tags. | Read only |
GET /campos | The lead's custom fields. | Read only |
A Read and write key also does everything a Read only key does. Route and field names are in Portuguese, the same in every language (etapa is stage, etiquetas are tags, campos are fields).
Just want to receive leads from a form or another tool, without a key or a server? Use the incoming webhooks: a secret URL that receives the lead with a POST.
Create the key
Keys are created by the account owner, and the account needs a plan or the free trial. Each account has up to 10 active keys: use one per system.
Step by step
- Sign in to Kaptia and open the More menu, then Integrations and API.
- Click New key and give it a name that says which system will use it, like "ERP" or "Website".
- Under What it can do, pick Read only (lists and reads leads, stages, tags and fields) or Read and write (also creates, changes and moves leads).
- Click Create key and copy it right away: once you close the window, it won't show again.
- Store it on the server, in an environment variable (
KAPTIA_API_KEY), and make a test call withGET /etapas.
After it is created
- The list shows the name, the last 4 characters, the scope, when it was created, the last use and how many calls it made.
- Revoke stops the key at once: the next request with it gets
401. It can't be undone, so create another one. - Lost the key? It can't be shown again: Kaptia only stores its hash. Revoke it and create another.
Authentication
The header
Send the key on every call, in the Authorization header, after the word Bearer and a space. It looks like kp_live_ followed by 43 letters, digits, - and _.
GET /api/v1/publica/etapas HTTP/1.1
Host: usekaptia.com
Authorization: Bearer kp_live_...Without the header, the response is 401 sem_chave; with a wrong or revoked key, 401 chave_invalida.
The key acts as the owner
The key does, only in its own account, what the owner who created it can do. It stops working at once when:
- it is revoked in the screen;
- whoever created it stops being the owner or is deactivated;
- the account is suspended.
In all three cases the response is 401 chave_invalida. With no plan or an overdue subscription, the key is still valid, but the API answers 402 until the account is back. Account in read-only mode: the key only reads, even if it is a read and write key.
Signing in to the screen does not open the API, and the key does not open the screen: the browser cookie of whoever is signed in does not count here.
Pagination and limits
Pagination
GET /leads returns leads from newest to oldest (by creation date), up to limite per page (1 to 100, default 50). The response includes proximo_cursor: for the next page, repeat the same request, with the same filters, plus cursor=<proximo_cursor>. When it comes back null, you are done.
The cursor is opaque: don't build or change it. A cursor that did not come from the previous page returns 422 cursor_invalido.
To sync with your system, store the time of the last fetch and request atualizado_desde with it, going through every page. Or receive the outgoing webhooks and use the fetch only to double check.
Limits
| Limit | Value |
|---|---|
| Requests per key | 120 per minute |
| Requests per IP | 300 per minute, across all keys |
| POST and PATCH body | 16 KB |
| Leads per page | 100 |
| Active keys per account | 10 |
| Outgoing webhooks per account | 10 |
| Tags per request | 20 |
| Custom fields per request | 30 |
Over the limit: 429 muitas_chamadas, with a Retry-After header saying how many seconds to wait.
Server side only
The API does not allow CORS for other sites: JavaScript running in a visitor's browser can't read the response, and the key would be visible to anyone. Always call it from your server (back end, function or API route). To send leads from a website form without a server, use the incoming webhooks.
Leads
The lead
Every lead route returns the lead in this shape:
{
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}| Field | What it is |
|---|---|
id | The lead id (uuid). |
nome | The card name. When created with empresa, it is the company name. |
telefone | Digits only, with the country code (14155550100), or null. |
email | Lowercase, or null. |
cidade, instagram, site | City, Instagram and website from the lead research. Instagram comes without the @. |
nicho | The niche key. With no niche, outros. |
notas | The card notes. |
valor_centavos | The deal value in cents (150000 = 1,500.00). |
origem | Where the card came from. A lead created by the API comes as site: they reached out to you. |
etapa | The stage, {id, chave, nome}. The key does not change when the stage is renamed. |
etiquetas | Tags, [{id, nome}], in alphabetical order. |
campos | The custom fields that have a value, always as text ("8", "sim"). |
criado_em | When the lead was created. |
atualizado_em | The last change to the card or its research. |
List leads
https://usekaptia.com/api/v1/publica/leads| Parameter | What it does |
|---|---|
etapa | Only leads in that stage, by key (novo) or id. A stage that doesn't exist: 422 etapa_inexistente. |
atualizado_desde | Only leads changed since that time. ISO 8601 with a time zone: 2026-11-25T14:00:00Z. |
busca | 1 to 100 characters. Searches name, email and city; with 6 digits or more, the phone too. |
limite | 1 to 100. Default 50. |
cursor | The proximo_cursor from the previous page (see Pagination). |
Any parameter outside the table returns 422 dados_invalidos. With a positive time zone (+01:00), encode the + as %2B; Z avoids that.
curl "https://usekaptia.com/api/v1/publica/leads?etapa=novo&busca=Alex&limite=1" \
-H "Authorization: Bearer $KAPTIA_API_KEY"{
"dados": [
{
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}
],
"proximo_cursor": "WyIyMDI2LTExLTI2VDE0OjAzOjEyLjQ4MVoiLCI4YzFmMmEzYi00ZDVlLTRmNjAtOGE3MS05MmIzYzRkNWU2ZjciXQ"
}Get one lead
https://usekaptia.com/api/v1/publica/leads/{id}Returns {"lead": {...}}. A lead that doesn't exist, belongs to another account, or an id that is not a uuid: 404 nao_encontrado.
curl "https://usekaptia.com/api/v1/publica/leads/8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7" \
-H "Authorization: Bearer $KAPTIA_API_KEY"{
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}
}Create a lead
https://usekaptia.com/api/v1/publica/leadsNeeds telefone or email; everything else is optional. Read and write key.
| Field | Type | What it is |
|---|---|---|
telefone | text, up to 40 | Phone with the country code (+1 415 555 0100). Without it, it gets the account's country code. 8 to 15 digits. |
email | text, up to 200 | Only counts if it looks like an email. |
nome | text, up to 160 | The person's name. |
empresa | text, up to 160 | Company. With it, the card takes the company name, and nome becomes the person's name in message greetings. |
notas | text, up to 2,000 | The card notes. |
cidade | text, up to 120 | The city. |
instagram | text, up to 60 | The profile, with or without the @. Out of format, it is dropped. Already on another lead in the account: 409. |
site | text, up to 300 | Website. Goes into the notes as site: .... |
nicho | text | The key of a niche that already exists in the account (lowercase, digits and hyphen). Without it, outros. |
origem | text, up to 80 | Where it came from. Goes into the note on the lead timeline. |
etapa | text | The key or id of the stage it starts in. Without it, New. |
etiquetas | list, up to 20 | Names (case insensitive) or ids of tags that already exist. |
campos | object, up to 30 | {"key": value} for custom fields. Value: text up to 300, number, true, false or null. |
curl -X POST "https://usekaptia.com/api/v1/publica/leads" \
-H "Authorization: Bearer $KAPTIA_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1042" \
-d '{
"nome": "Alex Morgan",
"empresa": "Example Studio",
"telefone": "+1 415 555 0100",
"email": "alex@example.com",
"cidade": "San Francisco",
"notas": "Wants a quote for 50 pieces.",
"etapa": "novo",
"etiquetas": [
"Website"
],
"campos": {
"team_size": 8
}
}'{
"criado": true,
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}
}{
"criado": false,
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}
}- A field outside the table:
422 dados_invalidos, with its name incampos(an extra field shows up ascorpo). - Stage, niche, tags and fields are checked before creating: one that doesn't exist rejects the whole request and nothing is saved.
- A lead with the same phone (with or without Brazil's ninth digit) or the same email already exists: you get
200withcriado: falseand that lead, with nothing changed. Only the email is added, if it had none. To change it, use Update. - The new lead is created with origin
api(until Nov 27, 2026 it wassite): it stays out of automatic prospecting, like form leads, and enters flows with the New lead created trigger. The timeline gets the noteChegou pela API (chave "<key name>"), with the origin and the notes.
Idempotency-Key
If the network drops in the middle of a POST /leads, you don't know whether the lead was created. Send the Idempotency-Key header with a value unique to each request (the order id in your system, or a UUID) and retry safely:
- The same key with the same body, within 24 hours: you get the SAME response (status and body), with the
Idempotent-Replayed: trueheader, and nothing new happens. - The same key with another body:
422 idempotency_key_reusada. The body is compared byte by byte: when retrying, send exactly the same text. - The first request still running:
409 em_andamento. Wait a moment and retry. - A request that failed (
4xxor5xx) is not stored: the same key can try again. - Up to 200 visible characters, no spaces. It applies per API key and only to
POST /leads.
Update a lead
https://usekaptia.com/api/v1/publica/leads/{id}Send only what changes (at least one field). Read and write key.
| Field | Type | What it does |
|---|---|---|
nome | text, 1 to 160 | Changes the card name. |
notas | text up to 2,000, or null | Changes the notes. null or "" clears them. |
etapa | text | The key or id. Moves the same way as Move stage. |
etiquetas | list, up to 20 | Replaces the WHOLE set: tags not sent are removed. [] removes all. |
campos | object, up to 30 | Only touches the fields sent. null clears a field's value. |
curl -X PATCH "https://usekaptia.com/api/v1/publica/leads/8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7" \
-H "Authorization: Bearer $KAPTIA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"notas": "Call on Friday at 10am.",
"etiquetas": [
"Website",
"Hot"
],
"campos": {
"team_size": 12
}
}'{
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Call on Friday at 10am.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "12"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T15:20:41.118Z"
}
}- Empty body or a field outside the table:
422 dados_invalidos. - Everything is checked before saving: with a tag that doesn't exist, nothing changes.
- Phone, email, city, Instagram and niche can't be changed through the API: only in the screen.
Move stage
https://usekaptia.com/api/v1/publica/leads/{id}/etapaBody {"etapa": "<key or id>"}. The response has mudou (false when it was already there) and the lead. The change goes on the timeline with API as the author, and starts the flow that enters on that stage and the lead.etapa_mudou webhook.
curl -X POST "https://usekaptia.com/api/v1/publica/leads/8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7/etapa" \
-H "Authorization: Bearer $KAPTIA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"etapa": "reuniao"
}'{
"mudou": true,
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Call on Friday at 10am.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "9e8d7c6b-5a4f-4e3d-8c2b-1a0f9e8d7c6b",
"chave": "reuniao",
"nome": "Meeting"
},
"etiquetas": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "12"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T15:22:05.903Z"
}
}Stages, tags and fields
The names and ids the lead routes accept. Any key can read them.
Stages
https://usekaptia.com/api/v1/publica/etapasThe pipeline stages in board order: {id, chave, nome, posicao}. In lead routes, the stage goes by key or id. The default keys are fixed (in Portuguese), even if the account renames the stage:
| Key | Default stage |
|---|---|
novo | New |
contatado | Contacted |
respondeu | Replied |
reuniao | Meeting |
fechado | Won |
perdido | Not interested |
A stage created by the account may come with chave: null: in that case, use the id.
curl "https://usekaptia.com/api/v1/publica/etapas" \
-H "Authorization: Bearer $KAPTIA_API_KEY"{
"dados": [
{
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New",
"posicao": 0
},
{
"id": "0d1c2b3a-4f5e-4a6b-8c7d-9e0f1a2b3c4d",
"chave": "contatado",
"nome": "Contacted",
"posicao": 1
},
{
"id": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
"chave": "respondeu",
"nome": "Replied",
"posicao": 2
},
{
"id": "9e8d7c6b-5a4f-4e3d-8c2b-1a0f9e8d7c6b",
"chave": "reuniao",
"nome": "Meeting",
"posicao": 3
},
{
"id": "c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f",
"chave": "fechado",
"nome": "Won",
"posicao": 4
},
{
"id": "e5f6a7b8-c9d0-4e1f-9a2b-3c4d5e6f7a8b",
"chave": "perdido",
"nome": "Not interested",
"posicao": 5
}
]
}Tags
https://usekaptia.com/api/v1/publica/etiquetasThe account's tags in alphabetical order, up to 500: {id, nome}. In lead routes, a tag goes by name (case insensitive) or by id. The API does not create tags: create them in the Kaptia screen.
curl "https://usekaptia.com/api/v1/publica/etiquetas" \
-H "Authorization: Bearer $KAPTIA_API_KEY"{
"dados": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
]
}Custom fields
https://usekaptia.com/api/v1/publica/camposThe fields the account created for the lead: {chave, nome, tipo, opcoes}. In lead routes, they go in campos, by key.
| Type | What it accepts |
|---|---|
texto | Text up to 300 characters. |
numero | The first number in the text: "8 people" becomes 8. Send a JSON number (1500.5): in text, the comma is read as the decimal separator ("1.500,50" becomes 1500.5, and "1,500" becomes 1.5). |
sim_nao | Yes or no: true or false, yes or no, sim or não, 1 or 0. Comes back as sim or nao. |
opcoes | One of the opcoes, ignoring case and accents. |
A value out of format: 422 valor_invalido. null (or empty text) clears the value.
curl "https://usekaptia.com/api/v1/publica/campos" \
-H "Authorization: Bearer $KAPTIA_API_KEY"{
"dados": [
{
"chave": "team_size",
"nome": "Team size",
"tipo": "numero",
"opcoes": []
},
{
"chave": "plan",
"nome": "Plan",
"tipo": "opcoes",
"opcoes": [
"Basic",
"Pro"
]
}
]
}Errors
Format
Every error comes with the code in erro and some text in mensagem. Always decide by erro: it does not change. mensagem is for people to read, it is in Portuguese, it may change and sometimes it is missing. Some errors bring an extra field: campos, campo, etiqueta or lead_id.
{
"erro": "dados_invalidos",
"mensagem": "Corpo inválido.",
"campos": [
"telefone"
]
}{
"erro": "etiqueta_inexistente",
"mensagem": "Essa etiqueta não existe na conta.",
"etiqueta": "Hot"
}The codes
| Status | Error | When it happens | What to do |
|---|---|---|---|
400 | json_invalido | The body is not valid JSON in UTF-8. | Check the JSON and the encoding. |
401 | sem_chave | Authorization: Bearer is missing. | Send the key. |
401 | chave_invalida | Wrong or revoked key, the creator is no longer the owner, or the account was suspended. | Check the key. Revoked: create another. |
402 | plano_necessario | The account has not subscribed to a plan yet. | Subscribe to a plan in Kaptia. |
402 | plano_vencido | The subscription is overdue. | Pay the subscription. |
403 | escopo_insuficiente | A Read only key (or a read-only account) trying to write. | Use a Read and write key. |
404 | nao_encontrado | The lead doesn't exist, belongs to another account, or the id is not a uuid. | Check the id. |
404 | rota_inexistente | A path or method the API doesn't have. | Check the routes table. |
409 | em_andamento | A request with the same Idempotency-Key is still running. | Wait a moment and retry. |
409 | instagram_de_outro_lead | The Instagram is already on another lead in the account (its id comes in lead_id). | Use the existing lead. |
409 | sem_funil | The account has no stages. | Set up the pipeline in Kaptia. |
413 | corpo_grande | Body over 16 KB. | Send less text. |
415 | tipo_nao_suportado | A Content-Type other than application/json. | Send JSON. |
422 | dados_invalidos | A field outside the list, a wrong type or a value too long (the names come in campos). | Fix the listed fields. |
422 | sem_telefone_nem_email | No valid phone and no valid email. | Send at least one of them. |
422 | etapa_inexistente | A stage that doesn't exist in the account. | Check Stages. |
422 | etiqueta_inexistente | A tag that doesn't exist (the name comes in etiqueta). | Check Tags or create it in the screen. |
422 | campo_inexistente | A custom field that doesn't exist (in campo). | Check Custom fields. |
422 | valor_invalido | A value that doesn't fit the field (in campo). | Check the field type. |
422 | nicho_inexistente | A niche that doesn't exist in the account. | Use the key of one of the account's niches. |
422 | cursor_invalido | A cursor that did not come from the previous page. | Use proximo_cursor. |
422 | idempotency_key_invalida | Over 200 characters, a space or an invisible character. | Use letters, digits and hyphens. |
422 | idempotency_key_reusada | The same Idempotency-Key with another body. | One new key per request. |
429 | muitas_chamadas | Over 120 per minute on the key or 300 per minute on the IP. | Wait for Retry-After and retry. |
500 | erro_interno | A failure on our side. | Try again, with increasing waits. |
When to retry
Retry on 429 (after Retry-After), on 409 em_andamento, on 5xx and when the connection drops. On POST /leads, send the same Idempotency-Key when retrying. On other 4xx, the same request will fail again: fix it first.
Outgoing webhooks
Kaptia notifies your system when something happens in the account: it sends a JSON POST to the address you register, signed with a secret unique to that address. Nothing waits for the delivery: the notice goes into a queue the moment the event happens and goes out within seconds.
Register the address
- Under More, Integrations, API, click New webhook.
- In Address (https), paste the URL of your system that will receive the notices.
- Under Events, tick what you want to receive (at least one).
- Click Create webhook and store the Secret (
whsec_...) on your server: it is what you use to check the signature. It stays on the webhook card, under Show the secret. - In the card menu, use Send test event: the notice goes out right away and the screen tells you whether it arrived, with the HTTP code and the time.
- Only the owner can register, and each account has up to 10 addresses.
- The address must be
httpson the default port, with a hostname (not an IP), no username or password, up to 500 characters. An address that points to an internal network, or that doesn't exist, is rejected when saving and again on every delivery. - On the card: the On switch, Edit (address and events), Generate new secret (the old one stops working at once) and Delete.
- Under Deliveries, the last 20, with the event, status, code and time. The notice content is not stored. The card also shows how many were delivered and how many failed in the last 7 days.
The events
| Event | When it fires | What comes in dados |
|---|---|---|
lead.criado | A lead is created in the account, by any path: screen, import, AI, incoming webhook, ad form or API. | lead |
lead.etapa_mudou | The lead changes stage: drag on the board, flow, AI or API. | lead, etapa_anterior |
lead.atualizado | The name, phone, notes, value, email, city, Instagram, niche, a custom field or the tags change. | lead |
venda.registrada | A new sale is recorded in Finance. | venda, lead |
contrato.assinado | A contract is signed through the link or marked as signed. | contrato, lead |
Board position, tasks, reminders and messages don't trigger notices. Several changes in a row to the same lead, before the first delivery, become one lead.atualizado with the newest state; and a lead created and changed before the delivery only fires lead.criado, already with the new data.
The notice
Each notice is a POST with these headers and a JSON body (it arrives on a single line; here it is broken up for reading):
POST /kaptia HTTP/1.1
Host: your-system.com
Content-Type: application/json
User-Agent: Kaptia-Webhooks/1.0
X-Kaptia-Evento: lead.criado
X-Kaptia-Entrega: d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a
X-Kaptia-Assinatura: t=1795701793,v1=d6231dae759be8afcf30d35134d21ed53619eeb101e306448a52a1026243215e
{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "lead.criado",
"criado_em": "2026-11-26T14:03:12.540Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}
}
}| Field | What it is |
|---|---|
id | The notice id (uuid), the same as the X-Kaptia-Entrega header. It doesn't change on retries: use it to avoid processing twice. |
evento | The event, the same as the X-Kaptia-Evento header. |
criado_em | When it happened (ISO 8601, UTC). |
conta | The account id in Kaptia. |
dados | What comes with the event (below). |
What comes in dados
lead has the same shape as The lead, as it was when the notice first went out (seconds after the event). If the lead was deleted before that, only {"id": ...} comes; a sale with no linked lead has lead: null.
{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "lead.criado",
"criado_em": "2026-11-26T14:03:12.540Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Wants a quote for 50 pieces.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "8"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T14:03:12.530Z"
}
}
}{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "lead.etapa_mudou",
"criado_em": "2026-11-26T15:22:05.910Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Call on Friday at 10am.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "9e8d7c6b-5a4f-4e3d-8c2b-1a0f9e8d7c6b",
"chave": "reuniao",
"nome": "Meeting"
},
"etiquetas": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "12"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T15:22:05.903Z"
},
"etapa_anterior": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
}
}
}{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "lead.atualizado",
"criado_em": "2026-11-26T15:20:41.130Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Call on Friday at 10am.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "5b0e7c1d-2f3a-4b8c-9d0e-1f2a3b4c5d6e",
"chave": "novo",
"nome": "New"
},
"etiquetas": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "12"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-26T15:20:41.118Z"
}
}
}{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "venda.registrada",
"criado_em": "2026-11-28T18:10:02.311Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"venda": {
"id": "6e5d4c3b-2a19-4f08-8e7d-6c5b4a392817",
"descricao": "50-piece package",
"cliente": "Example Studio",
"valor_centavos": 150000,
"moeda": "USD",
"data": "2026-11-28",
"criada_em": "2026-11-28T18:10:02.311Z"
},
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Call on Friday at 10am.",
"valor_centavos": 150000,
"origem": "api",
"etapa": {
"id": "c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f",
"chave": "fechado",
"nome": "Won"
},
"etiquetas": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "12"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-28T18:07:44.120Z"
}
}
}{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "contrato.assinado",
"criado_em": "2026-11-28T18:07:44.090Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"contrato": {
"id": "3b2a1908-7f6e-4d5c-8b4a-392817f6e5d4",
"titulo": "Services agreement",
"assinado_em": "2026-11-28T18:07:44.071Z"
},
"lead": {
"id": "8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7",
"nome": "Example Studio",
"telefone": "14155550100",
"email": "alex@example.com",
"cidade": "San Francisco",
"instagram": null,
"site": null,
"nicho": "outros",
"notas": "Call on Friday at 10am.",
"valor_centavos": 0,
"origem": "api",
"etapa": {
"id": "9e8d7c6b-5a4f-4e3d-8c2b-1a0f9e8d7c6b",
"chave": "reuniao",
"nome": "Meeting"
},
"etiquetas": [
{
"id": "7f1e3d5c-9b2a-4c8e-a6d4-2f0e8c6a4b2d",
"nome": "Hot"
},
{
"id": "2c4e6a8b-1d3f-4a5c-8e7b-9d1f3a5c7e9b",
"nome": "Website"
}
],
"campos": {
"team_size": "12"
},
"criado_em": "2026-11-26T14:03:12.481Z",
"atualizado_em": "2026-11-28T18:07:44.090Z"
}
}
}{
"id": "d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a",
"evento": "teste",
"criado_em": "2026-11-26T14:05:00.000Z",
"conta": "7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d",
"dados": {
"mensagem": "Evento de teste do Kaptia. Se chegou, a assinatura e o endereço estão certos."
}
}etapa_anterior:{id, chave, nome}of the stage it left.venda:{id, descricao, cliente, valor_centavos, moeda, data, criada_em}. The value is in cents in the sale's currency (150000inUSD= $1,500.00) anddatais the sale day (YYYY-MM-DD).contrato:{id, titulo, assinado_em}.teste: only sent by the Send test event button, withdados.mensagem. It has no retries and doesn't count toward the address failures.
Check the signature
The X-Kaptia-Assinatura header looks like t=<seconds>,v1=<hex>: t is the delivery time (Unix, in seconds) and v1 is the HMAC-SHA256, in lowercase hex, computed with the webhook secret over the text <t>.<body>.
- Read the raw body, before parsing it as JSON: serializing it again changes the bytes and the math won't match.
- Split
tandv1from the header. - Compute the HMAC-SHA256 with the whole secret (including
whsec_) overt, a dot and the body. - Compare with
v1in constant time (timingSafeEqual,hash_equals,compare_digest). - Reject it if
tis more than 5 minutes away from your clock.
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
// The webhook secret (whsec_...), in an environment variable.
const SECRET = process.env.KAPTIA_WEBHOOK_SECRET;
const TOLERANCE = 300; // 5 min
// Check against the RAW body: the bytes that arrived, before parsing the JSON.
function validSignature(rawBody, header) {
const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header || "");
if (!match) return false;
// Older than 5 minutes: stale notice, reject it.
if (Math.abs(Date.now() / 1000 - Number(match[1])) > TOLERANCE) return false;
const expected = createHmac("sha256", SECRET).update(match[1] + "." + rawBody).digest();
return timingSafeEqual(expected, Buffer.from(match[2], "hex"));
}
const seen = new Set(); // in production, store the ids in a database
createServer((req, res) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const rawBody = Buffer.concat(chunks).toString("utf8");
if (!validSignature(rawBody, req.headers["x-kaptia-assinatura"])) {
res.writeHead(401).end();
return;
}
// Answer 2xx right away (within 5 s) and process later.
res.writeHead(200).end();
const event = JSON.parse(rawBody);
// Already processed this id? Ignore it: it is a retry.
if (seen.has(event.id)) return;
seen.add(event.id);
console.log(event.evento, event.dados.lead?.id);
});
}).listen(3000);<?php
// The webhook secret (whsec_...), in an environment variable.
$secret = getenv('KAPTIA_WEBHOOK_SECRET');
// Check against the RAW body: the bytes that arrived, before parsing the JSON.
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_KAPTIA_ASSINATURA'] ?? '';
if (!preg_match('/^t=(\d+),v1=([0-9a-f]{64})$/', $header, $m)) {
http_response_code(401);
exit;
}
// Older than 5 minutes: stale notice, reject it.
if (abs(time() - (int) $m[1]) > 300) {
http_response_code(401);
exit;
}
$expected = hash_hmac('sha256', $m[1] . '.' . $rawBody, $secret);
if (!hash_equals($expected, $m[2])) {
http_response_code(401);
exit;
}
// Answer 2xx right away (within 5 s) and process later.
http_response_code(200);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
$event = json_decode($rawBody, true);
// Already processed this id? Ignore it: it is a retry.
error_log($event['evento'] . ' ' . $event['id']);import hashlib
import hmac
import json
import os
import re
import time
# The webhook secret (whsec_...), in an environment variable.
SECRET = os.environ["KAPTIA_WEBHOOK_SECRET"].encode("utf-8")
# Check against the RAW body: the bytes that arrived, before parsing the JSON.
def valid_signature(raw_body: bytes, header: str) -> bool:
match = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
if not match:
return False
# Older than 5 minutes: stale notice, reject it.
if abs(time.time() - int(match.group(1))) > 300:
return False
expected = hmac.new(SECRET, match.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, match.group(2))
# With Flask:
from flask import Flask, request
app = Flask(__name__)
@app.post("/kaptia")
def kaptia():
raw_body = request.get_data()
if not valid_signature(raw_body, request.headers.get("X-Kaptia-Assinatura", "")):
return "", 401
event = json.loads(raw_body)
# Already processed this id? Ignore it: it is a retry.
print(event["evento"], event["id"])
return "", 200A framework that parses the body as JSON before you do (express.json(), for example) breaks the math: on that route, read the raw body.
Test vector
To check your code without waiting for a notice: with this secret, this t and this body (a single line, exactly like this), the header must come out the same as in the last tab. When testing, turn off the 5 minute check: this t is from Nov 26, 2026.
whsec_exemplo_do_vetor_de_teste1795701900{"id":"d4c3b2a1-6f5e-4d3c-9b2a-0f1e2d3c4b5a","evento":"teste","criado_em":"2026-11-26T14:05:00.000Z","conta":"7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d","dados":{"mensagem":"Evento de teste do Kaptia. Se chegou, a assinatura e o endereço estão certos."}}t=1795701900,v1=8bad2d1cbc4315b518120612d975575e2e9ff8a7ad0c1dc8713fd6f22d181f0cDelivery and retries
A 2xx response within 5 seconds counts as delivered; the body of your response isn't even read. Anything else (another code, a slow answer, a refused connection, a redirect) is a failure, and Kaptia retries:
| Attempt | When |
|---|---|
| 1st | Seconds after the event. |
| 2nd | 1 minute after the 1st failure. |
| 3rd | 5 minutes later. |
| 4th | 30 minutes later. |
| 5th | 2 hours later. |
| 6th | 6 hours later. If it fails again, the notice is marked Failed. |
- Every attempt carries the same body, with the same
id.tand the signature are computed again on each attempt. - Redirects (
3xx) are not followed: register the final address. - After 15 attempts in a row without success (counting all notices), the webhook turns itself off, the notices waiting in the queue are cancelled and the card tells you. Turning it back on resets the count, but what was cancelled doesn't come back: fetch it with
GET /leads?atualizado_desde=. - A delivery with
2xxresets the failures in a row. - Generated a new secret? The next attempts are already signed with it.
Good practices
- Answer
2xxright away and process the notice later, in a queue on your side. - Store the
idof every processed notice and ignore repeats. - Arrival order is not guaranteed (several notices go out together, and there are retries): compare the lead's
atualizado_emand, when in doubt, read the lead through the API. - What your system changes through the API also triggers notices: be careful not to create a loop.
- Were you offline? Recover what you missed with
GET /leads?atualizado_desde=.
Full examples
The same steps in each language: create the lead with an Idempotency-Key, move it to Meeting and fetch what changed in the last 24 hours, page by page, waiting for Retry-After on 429. The key comes from the KAPTIA_API_KEY environment variable.
# 1. Create the lead (or find the one that already exists). The same Idempotency-Key never creates twice.
curl -X POST "https://usekaptia.com/api/v1/publica/leads" \
-H "Authorization: Bearer $KAPTIA_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1042" \
-d '{
"nome": "Alex Morgan",
"empresa": "Example Studio",
"telefone": "+1 415 555 0100",
"email": "alex@example.com",
"cidade": "San Francisco",
"notas": "Wants a quote for 50 pieces.",
"etapa": "novo",
"etiquetas": [
"Website"
],
"campos": {
"team_size": 8
}
}'
# 2. Move it to Meeting.
curl -X POST "https://usekaptia.com/api/v1/publica/leads/8c1f2a3b-4d5e-4f60-8a71-92b3c4d5e6f7/etapa" \
-H "Authorization: Bearer $KAPTIA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"etapa": "reuniao"
}'
# 3. What changed in the last 24 hours, page by page.
curl "https://usekaptia.com/api/v1/publica/leads?atualizado_desde=2026-11-25T14:00:00Z&limite=100" \
-H "Authorization: Bearer $KAPTIA_API_KEY"
# 4. The next page: the same request, with the proximo_cursor from the response.
curl "https://usekaptia.com/api/v1/publica/leads?atualizado_desde=2026-11-25T14:00:00Z&limite=100&cursor=WyIyMDI2LTExLTI2VDE0OjAzOjEyLjQ4MVoiLCI4YzFmMmEzYi00ZDVlLTRmNjAtOGE3MS05MmIzYzRkNWU2ZjciXQ" \
-H "Authorization: Bearer $KAPTIA_API_KEY"// On your server: the key lives in an environment variable, never in the browser.
const API = "https://usekaptia.com/api/v1/publica";
const KEY = process.env.KAPTIA_API_KEY; // kp_live_...
async function kaptia(method, path, body, extraHeaders = {}) {
const headers = { Authorization: "Bearer " + KEY, ...extraHeaders };
if (body !== undefined) headers["Content-Type"] = "application/json";
for (let attempt = 1; ; attempt++) {
const response = await fetch(API + path, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(15000),
});
// 429: wait for Retry-After and try again (up to 3 times).
if (response.status === 429 && attempt <= 3) {
const wait = Number(response.headers.get("Retry-After") || 60);
await new Promise((resolve) => setTimeout(resolve, wait * 1000));
continue;
}
const data = await response.json();
if (!response.ok) throw new Error("Kaptia " + response.status + ": " + data.erro);
return data;
}
}
// 1. Create the lead (or find the one that already exists). The same Idempotency-Key never creates twice.
const { criado, lead } = await kaptia("POST", "/leads", {
"nome": "Alex Morgan",
"empresa": "Example Studio",
"telefone": "+1 415 555 0100",
"email": "alex@example.com",
"cidade": "San Francisco",
"notas": "Wants a quote for 50 pieces.",
"etapa": "novo",
"etiquetas": [
"Website"
],
"campos": {
"team_size": 8
}
}, { "Idempotency-Key": "order-1042" });
console.log(criado, lead.id);
// 2. Move it to Meeting.
await kaptia("POST", "/leads/" + lead.id + "/etapa", { etapa: "reuniao" });
// 3. What changed in the last 24 hours, page by page.
const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
let cursor = null;
do {
const query = new URLSearchParams({ atualizado_desde: since, limite: "100" });
if (cursor) query.set("cursor", cursor);
const page = await kaptia("GET", "/leads?" + query);
for (const item of page.dados) console.log(item.id, item.nome, item.etapa.chave);
cursor = page.proximo_cursor;
} while (cursor);<?php
// On your server: the key lives in an environment variable, never in the browser.
const KAPTIA_API = 'https://usekaptia.com/api/v1/publica';
function kaptia(string $method, string $path, ?array $body = null, array $headers = []): array
{
$headers[] = 'Authorization: Bearer ' . getenv('KAPTIA_API_KEY');
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
}
for ($attempt = 1; ; $attempt++) {
$ch = curl_init(KAPTIA_API . $path);
$options = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_TIMEOUT => 15,
];
if ($body !== null) {
$options[CURLOPT_POSTFIELDS] = json_encode($body);
}
curl_setopt_array($ch, $options);
$raw = (string) curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseHeaders = substr($raw, 0, $headerSize);
$data = json_decode(substr($raw, $headerSize), true) ?? [];
// 429: wait for Retry-After and try again (up to 3 times).
if ($status === 429 && $attempt <= 3) {
sleep(preg_match('/^retry-after:\s*(\d+)/mi', $responseHeaders, $m) ? (int) $m[1] : 60);
continue;
}
if ($status >= 400) {
throw new RuntimeException("Kaptia $status: " . ($data['erro'] ?? ''));
}
return $data;
}
}
// 1. Create the lead (or find the one that already exists). The same Idempotency-Key never creates twice.
$result = kaptia('POST', '/leads', [
'nome' => 'Alex Morgan',
'empresa' => 'Example Studio',
'telefone' => '+1 415 555 0100',
'email' => 'alex@example.com',
'cidade' => 'San Francisco',
'notas' => 'Wants a quote for 50 pieces.',
'etapa' => 'novo',
'etiquetas' => ['Website'],
'campos' => [
'team_size' => 8,
],
], ['Idempotency-Key: order-1042']);
$lead = $result['lead'];
// 2. Move it to Meeting.
kaptia('POST', '/leads/' . $lead['id'] . '/etapa', ['etapa' => 'reuniao']);
// 3. What changed in the last 24 hours, page by page.
$since = gmdate('Y-m-d\TH:i:s\Z', time() - 86400);
$cursor = null;
do {
$query = ['atualizado_desde' => $since, 'limite' => 100];
if ($cursor) {
$query['cursor'] = $cursor;
}
$page = kaptia('GET', '/leads?' . http_build_query($query));
foreach ($page['dados'] as $item) {
echo $item['id'], ' ', $item['nome'], ' ', $item['etapa']['chave'], PHP_EOL;
}
$cursor = $page['proximo_cursor'];
} while ($cursor);import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
# On your server: the key lives in an environment variable, never in the browser.
API = "https://usekaptia.com/api/v1/publica"
KEY = os.environ["KAPTIA_API_KEY"] # kp_live_...
def kaptia(method, path, body=None, headers=None):
all_headers = {"Authorization": "Bearer " + KEY, **(headers or {})}
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
all_headers["Content-Type"] = "application/json"
for attempt in range(1, 5):
request = urllib.request.Request(API + path, data=data, headers=all_headers, method=method)
try:
with urllib.request.urlopen(request, timeout=15) as response:
return json.load(response)
except urllib.error.HTTPError as error:
# 429: wait for Retry-After and try again (up to 3 times).
if error.code == 429 and attempt <= 3:
time.sleep(int(error.headers.get("Retry-After", "60")))
continue
raise RuntimeError("Kaptia %d: %s" % (error.code, json.load(error).get("erro")))
# 1. Create the lead (or find the one that already exists). The same Idempotency-Key never creates twice.
result = kaptia("POST", "/leads", {
"nome": "Alex Morgan",
"empresa": "Example Studio",
"telefone": "+1 415 555 0100",
"email": "alex@example.com",
"cidade": "San Francisco",
"notas": "Wants a quote for 50 pieces.",
"etapa": "novo",
"etiquetas": [
"Website"
],
"campos": {
"team_size": 8
}
}, {"Idempotency-Key": "order-1042"})
lead = result["lead"]
print(result["criado"], lead["id"])
# 2. Move it to Meeting.
kaptia("POST", "/leads/" + lead["id"] + "/etapa", {"etapa": "reuniao"})
# 3. What changed in the last 24 hours, page by page.
since = (datetime.now(timezone.utc) - timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
cursor = None
while True:
params = {"atualizado_desde": since, "limite": 100}
if cursor:
params["cursor"] = cursor
page = kaptia("GET", "/leads?" + urllib.parse.urlencode(params))
for item in page["dados"]:
print(item["id"], item["nome"], item["etapa"]["chave"])
cursor = page["proximo_cursor"]
if not cursor:
breakTo receive notices, the server examples are in Check the signature.
Security
- The key is as good as a password to the account: keep it only on the server, in an environment variable. Never in the browser, a mobile app, the repository, a spreadsheet or a screenshot.
- Least scope: reports, dashboards and BI use Read only. Read and write only for whatever creates or changes leads.
- One key per system, with a name that says which one. That way you can revoke one without stopping the others, and the screen shows the last use and the calls of each.
- Leaked, or you suspect it? Revoke it right away: the next request with it already gets
401. Then create another and swap it on the server. - Kaptia only stores the key's hash (SHA-256): not even our team can show it again.
- Everything is tied to the key's account: a lead, stage, tag or field from another account returns
404or422, as if it didn't exist. - On outgoing webhooks, check the signature on every notice, reject
tolder than 5 minutes and keep the secret out of the code. Leaked: Generate new secret (the old one stops working at once). - Kaptia only sends notices to public
https: an internal network address is rejected when saving and again on every delivery, and redirects are not followed.
FAQ
Who can create the API key?
Only the account owner, under More, Integrations, API. The key acts on their behalf: if they stop being the owner, are deactivated or the account is suspended, the key stops working right away.
Do I need a plan to use the API?
Yes. The account must have a plan or be on the free trial. With no plan the API answers 402 plano_necessario and, with an overdue subscription, 402 plano_vencido. Creating keys and webhooks also requires an active account.
Can I call the API straight from the browser or an app?
No. The API does not allow CORS for other sites, and the key would be visible to anyone. Call it from your server. To send leads from a website form without a server, use the incoming webhooks.
Does sending the same lead twice create two?
No. The same phone number (with or without Brazil's ninth digit) or the same email returns the lead that already exists, with status 200 and criado false. With an Idempotency-Key, the same request repeated returns exactly the same response.
I sent a stage and tags in the POST and the lead did not change. Why?
Because the lead already existed. The POST does not touch an existing lead (it only fills in the email if it had none). To change it, use PATCH /leads/{id} or POST /leads/{id}/etapa with the id from the response.
Can I delete a lead or send messages through the API?
No. The API creates, reads, changes and moves leads. Deleting is done in the Kaptia screen, and messages to the lead go out through flows: a lead created by the API enters the flows with the New lead trigger, and moving a stage starts the flow that enters on that stage.
How do I know a notice really came from Kaptia?
Check the X-Kaptia-Assinatura header: compute the HMAC-SHA256 of the webhook secret over t, a dot and the raw body, compare it with v1 and reject it if t is more than 5 minutes old.
I got the same notice twice. Is that a bug?
It can happen: if your 2xx answer did not arrive within 5 seconds, Kaptia retries with the same id. Store the ids you already processed and ignore repeats.
The webhook turned itself off. What now?
After 15 attempts in a row without a 2xx it turns off, and the notices waiting in the queue are cancelled. Check the address, use Send test event and turn it back on. What was left behind is not resent: fetch it with GET /leads and the atualizado_desde filter.
Does it work with Zapier and Make?
It does. To call the API, use the tool's HTTP request with the Authorization: Bearer header and the key. To receive the outgoing webhooks, register in Kaptia the https address of the tool's webhook trigger.
What are the limits?
120 requests per minute per key and 300 per minute per IP, up to 100 leads per page, bodies up to 16 KB, and 10 keys and 10 webhooks per account.
Integrate with your AI
Going to ask an AI to build the integration? Copy one of the prompts and paste it into Claude, ChatGPT or Cursor. They point to this page, which the AI can read in full (it comes ready from the server), and to the Kaptia summary written for machines.
https://usekaptia.com/en/docs/apihttps://usekaptia.com/llms.txtI want to integrate my system with the Kaptia API (a CRM).
Read the whole documentation first: https://usekaptia.com/en/docs/api
Product summary: https://usekaptia.com/llms.txt
What matters:
- Base: https://usekaptia.com/api/v1/publica. Every call carries Authorization: Bearer <kp_live_... key>, always from the server (no CORS).
- Routes: GET /leads (etapa, atualizado_desde, busca, limite up to 100, cursor), GET /leads/{id}, POST /leads (optional Idempotency-Key), PATCH /leads/{id}, POST /leads/{id}/etapa, GET /etapas, GET /etiquetas, GET /campos. Field names are in Portuguese.
- POST /leads needs telefone (with the country code) or email. A lead that already exists comes back 200 with criado: false, unchanged; to change it, PATCH.
- Errors: {erro, mensagem}; decide by erro. 429: wait for Retry-After (120 per minute per key).
- Outgoing webhooks: POST with {id, evento, criado_em, conta, dados}. Check X-Kaptia-Assinatura: t=<seconds>,v1=<hex>, the HMAC-SHA256 of the whsec_ secret over "<t>.<raw body>"; reject t older than 5 minutes, answer 2xx within 5 s and ignore repeated ids.
What I want to do: [describe it here: send my website leads, sync with my ERP, notify my system when a lead is won...]
My language and framework: [e.g. Node with Express, PHP with Laravel, Python with Django]
Give me the steps and the code.You are going to help me connect my system to Kaptia, a CRM, through the API with a key and the outgoing webhooks.
Source of truth (read it first, the whole page): https://usekaptia.com/en/docs/api
Product summary: https://usekaptia.com/llms.txt
Summary:
- Base https://usekaptia.com/api/v1/publica, header Authorization: Bearer kp_live_... (key created by the owner under More, Integrations, API; read only or read and write).
- Server side only: the API doesn't allow CORS and the key can't go to the browser.
- Leads: list with pages (proximo_cursor), get, create (telefone or email; the same phone or email returns the existing lead), update (etiquetas replaces the whole set) and move stage by key (novo, contatado, respondeu, reuniao, fechado, perdido) or by id.
- Errors are always {erro, mensagem}. 429 with Retry-After. 120 requests per minute per key.
- Outgoing webhooks: lead.criado, lead.etapa_mudou, lead.atualizado, venda.registrada, contrato.assinado. HMAC-SHA256 signature in X-Kaptia-Assinatura (t=...,v1=...) over "<t>.<raw body>". Retries keep the same id.
Start by asking me what I want to integrate and in which language. Then guide me step by step and tell me how to test it.Integrate the Kaptia API (CRM) into this project.
Full documentation (read it before writing code): https://usekaptia.com/en/docs/api
Rules:
- Call it only from the SERVER (API route, server action or function), never from the browser: the API doesn't allow CORS and the key is secret.
- Read the key from KAPTIA_API_KEY and, if you will receive webhooks, the secret from KAPTIA_WEBHOOK_SECRET. Add both to .env.example without values.
- Base https://usekaptia.com/api/v1/publica, header Authorization: Bearer <key>, Content-Type: application/json when there is a body.
- When creating a lead (POST /leads), send an Idempotency-Key with the record id in our system, and telefone with the country code.
- Errors: decide by the erro field. 429 and 5xx: up to 3 retries, honoring Retry-After. Other 4xx: log them and don't retry.
- Outgoing webhooks: read the raw body, check X-Kaptia-Assinatura (t=<seconds>,v1=<hex>, HMAC-SHA256 of the secret over "<t>.<body>") in constant time, reject t older than 5 minutes, answer 200 right away and never process the same id twice.
- 15 s timeout. If Kaptia fails, our system must not go down with it: log and move on.
- Show where each call ended up and how to test it.Or use Copy page as Markdown, at the top, and paste the whole doc along with the prompt.
Write to us. The people who answer are the people who built it.
contato@usekaptia.comReceive leads from forms, Zapier, Make, WordPress and Google Forms with a POST, no key needed.
