HelpDevelopers

Integrate with Surveyr

Read surveys and every response, get signed webhooks as responses arrive, and track your usage: from your first call to production, with test keys that never send a WhatsApp message.

Part 1

Your first call in five minutes

  1. Make a test key

    • In Surveyr, open Settings → API (organisation owners) and choose New key.
    • Pick Test. A test key starts svk_test_, reads made-up surveys and responses, and never sends a message or touches real data. It is free.
    • Copy the key now: it is shown once. Keep it on your server, never in a browser or app.

    Tip: Live keys (svk_live_) read your real data. Make one when your integration works with the test key.

  2. Put the key in a variable

    • export SURVEYR_API_KEY=svk_test_… so it never ends up in a copied command or a log.
  3. Call /me

    • It answers with your organisation, the key's scopes, your plan and its limits.
curl "https://www.surveyr.africa/api/external/v2/me" \
  -H "x-api-key: $SURVEYR_API_KEY"
Response
{
  "data": {
    "organization": {
      "id": "Ab12Cd",
      "name": "Acme"
    },
    "key": {
      "id": "6721…",
      "environment": "test",
      "scopes": [
        "responses:read",
        "surveys:read"
      ]
    },
    "plan": {
      "plan": "starter",
      "name": "Starter",
      "status": "active",
      "enforced": true,
      "limits": {
        "perMinute": 120,
        "monthlyRequests": 100000,
        "webhooks": 5,
        "liveKeys": true
      }
    },
    "limits": {
      "maxPageSize": 500
    },
    "serverTime": "2026-11-10T08:00:00.000Z"
  },
  "meta": {
    "requestId": "req_8sJ2…",
    "apiVersion": "v2"
  },
  "error": null
}

Then list your surveys and read responses. With a test key you get two sandbox surveys and their responses, including a corrected report, an unfinished form and a deletion notice, so you can build for every case before going live.

curl "https://www.surveyr.africa/api/external/v2/surveys" \
  -H "x-api-key: $SURVEYR_API_KEY"

curl "https://www.surveyr.africa/api/external/v2/surveys/$SURVEY_ID/responses?limit=10" \
  -H "x-api-key: $SURVEYR_API_KEY"

Machine-readable reference: OpenAPI 3.1. There is also a Postman collection and an llms.txt for AI coding assistants.

Part 2

How every call behaves

  • Base URL https://www.surveyr.africa/api/external/v2. Send the key in the x-api-key header.
  • Every answer is { "data": …, "meta": { "requestId", "apiVersion": "v2", … }, "error": null }. An error has data: null and error: { code, message, details }. Quote meta.requestId (also the X-Request-Id header) to support.
  • error.code is stable: branch on it, not on message, which may change.
  • Lists are cursor-paginated: when meta.hasMore is true, pass meta.nextCursor back as cursor. A cursor keeps the first page's time window, so no record falls between pages.
  • updatedSince (and until) take an ISO 8601 time with Z or an offset, or a time back from now: 30m, 2h, 1d (up to 90d). For incremental sync, overlap your windows by a few minutes and de-duplicate on id.
  • Every response is keyed by the question's stable id, which never changes when questions are reordered, renamed or translated.
  • All times are UTC. All ids are strings.
Statuserror.codeWhat to do
400validation_failed, bad_request, idempotency_key_requiredFix the request; details.field names the field
401api_key_required, unauthorizedSend a valid key; it may have been revoked or rotated
402quota_exceeded, payment_required, account_suspendedAbout your plan, not your speed: see GET /usage
403insufficient_scope, forbiddenThe key lacks details.required, or can't do this
404not_foundNo such thing in your organisation (other organisations' data is always 404)
409conflict, idempotency_in_progressRetry later, or change what conflicts
422idempotency_key_reusedUse a new Idempotency-Key for a different request
429rate_limitedWait Retry-After seconds
5xxserver_error, unavailableRetry with backoff (POSTs with the same Idempotency-Key)
503maintenanceSurveyr is down for maintenance: wait Retry-After seconds, then try again

Idempotency. Send an Idempotency-Key header (a UUID) on every POST that creates or sends. A retry with the same key gets the first answer back, marked Idempotent-Replayed: true, and nothing is done twice. Keys are kept for 24 hours.

Rate limits and quotas. Every answer carries X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (per key, per minute) and X-Quota-Limit, X-Quota-Remaining, X-Quota-Reset (per organisation, per calendar month, UTC). Only successful requests count toward the quota.

Versions. v2 only ever gains fields, routes and error codes; anything breaking goes into a new version, announced at least 6 months ahead with a Sunset header on the old one. Ignore fields you don't know. v1 (/api/external/v1, the read-only feed in Connect to the Surveyr API) keeps working unchanged.

Part 3

Keys, scopes and rotation

ScopeLets the key
surveys:readRead surveys, their questions and share links
responses:readRead responses, including respondents' names and numbers
webhooks:manageCreate, change and delete webhooks, see deliveries and replay them (response events also need responses:read)
  • Give each integration its own key with only the scopes it needs. A key only works on the API, never on the Surveyr dashboard's routes.
  • Rotate a key in Settings → API: you get a new key with the same scopes, and the old one keeps working for the grace period you choose (24 hours by default), so you can deploy the new one without downtime.
  • Revoke a key and it stops working at once.
  • Contacts, distributions (sending surveys over WhatsApp) and write scopes are on the way; Settings → API lists them as planned.
Part 4

Webhooks: get responses as they arrive

Instead of polling, register an HTTPS endpoint and Surveyr POSTs each event to it, signed with the Standard Webhooks scheme (any Standard Webhooks library verifies it).

curl -X POST "https://www.surveyr.africa/api/external/v2/webhooks" \
  -H "x-api-key: $SURVEYR_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com/hooks/surveyr","events":["response.completed","response.updated","response.deleted"]}'

The answer carries the webhook's secret (whsec_…) once. Store it; you need it to verify signatures. A retry with the same Idempotency-Key answers without it (secret: null). POST /webhooks/{id}/rotate-secret makes a new one, and both sign during the grace period. Webhooks need a live key: test keys never write or send anything.

EventWhen
response.createdA new report was stored, finished or not (status complete or incomplete)
response.completedA finished report was stored
response.updatedA correction stored a new version (version > 1, replacesId set)
response.deletedA report was deleted: the record is a deletion notice
response.alertA response matched one of its survey's answer alerts (Overview → Alerts, with "Webhook (your system)" ticked); alert names the rules it matched
webhook.testPOST /webhooks/{id}/test, with a sample record
What your endpoint receives
{
  "type": "response.completed",
  "timestamp": "2026-11-10T08:01:12.000Z",
  "webhookId": "6731…",
  "data": {
    "id": "6909c2a1…",
    "surveyId": "6900aa00…",
    "reportId": "6909c2a1…",
    "version": 1,
    "status": "complete",
    "latest": true,
    "respondent": null,
    "answers": {
      "q1": {
        "value": "Yes",
        "answered": true,
        "followUps": [
          {
            "question": "What time did it open?",
            "answer": "At seven"
          }
        ]
      }
    }
  }
}
  • Each answer has followUps: the follow-up the AI asked after it, as [{ question, answer }] in the order asked, or [] when it asked none. When the person wrote again before the AI had asked, question is the fixed text (The person added this before the follow-up) and answer is what they wrote. It is on v2 records and webhooks only (v1 never has it).
  • Each answer and follow-up has sentiment: { emotion, score, model, probabilities }, or null for a picked option. It starts as the word list's score (model: "afinn", probabilities: null), and a webhook is usually sent before the AI has read the answer, so it carries that score. Where AI sentiment is switched on, shortly after the save the AI's result (model: "decisions:gpt-6-luna", with the four probabilities) is written and the record's sentimentAt set, without moving updatedAt: fetch GET /responses/{id} to read it. v2 only.
  • data is exactly the record GET /responses/{id} returns. The respondent's name, number and properties are left out unless you create the webhook with "includeRespondent": true.
  • response.alert comes once per run when a response (or an unfinished form, when the person stopped after the answer) matches a rule of the survey's answer alert. It adds alert: the rules it matched, as { "rules": [{ "questionId", "optionIds" }] }, or for a rule on negative answers { "kind": "sentiment", "label": "negative", "questionIds", "threshold" } (sent shortly after the save, once the AI has read the answers); the answers are in data.answers. An alert on an answer that suggests someone may be at risk is never sent to a webhook.
  • Headers: webhook-id (the same on every retry: de-duplicate on it), webhook-timestamp, webhook-signature.
  • Answer with any 2xx within 10 seconds. Anything else is retried after 5 s, 5 min, 30 min, 2 h, 5 h, 10 h and 10 h. A webhook whose events keep failing for a day, or that answers 410 Gone, is switched off and your owners are notified; PATCH /webhooks/{id} with "status": "active" switches it back on.
  • GET /webhooks/{id}/deliveries shows every attempt (status code, timing) for 30 days; POST …/deliveries/{deliveryId}/replay sends one again.
  • Webhooks only call public HTTPS addresses.
import crypto from "node:crypto";

// Verify a Surveyr webhook (Standard Webhooks). Use the RAW request body, not parsed JSON.
export function verifySurveyrWebhook(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = Number(headers["webhook-timestamp"]);
  if (!id || !Number.isInteger(timestamp)) return false;
  if (Math.abs(Date.now() / 1000 - timestamp) > 300) return false; // older than 5 minutes
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = "v1," + crypto.createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64");
  return String(headers["webhook-signature"] || "").split(" ").some((signature) =>
    signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)));
}

// Express: keep the raw body for this route.
app.post("/hooks/surveyr", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifySurveyrWebhook(process.env.SURVEYR_WEBHOOK_SECRET, req.headers, req.body.toString("utf8"))) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body);
  queue.add(event); // answer fast (within 10 s); do the work afterwards
  res.sendStatus(204);
});
Recipe 1

Push responses into your CRM

  1. Make a live key

    • Scopes responses:read and webhooks:manage.
  2. Register a webhook

    • Events response.completed, response.updated and response.deleted; optionally surveyIds to limit it to some surveys.
  3. Upsert by reportId

    • Every version of one report shares reportId, so a correction updates the same CRM record instead of making a second one.
  4. Backfill once

    • Pull GET /responses from the start (cursor through every page) so the CRM has what came before the webhook.
// One upsert per report: every version of a report shares reportId.
async function handle(event) {
  const record = event.data;
  switch (event.type) {
    case "response.completed": // a new report
    case "response.updated":   // a correction: the new version replaces the old one
      await crm.upsert({ externalId: record.reportId, version: record.version, answers: record.answers, updatedAt: record.updatedAt });
      break;
    case "response.deleted":   // a deletion notice
      await crm.remove({ externalId: record.reportId ?? record.id });
      break;
  }
}
// Retries and replays send the same webhook-id: skip one you have already handled.
Recipe 2

Trigger a survey from your HR or ops system

GET /surveys/{id}/links gives the survey's WhatsApp start link (to your own number once you've connected one) and, when anyone with the link can answer it on the web, its web link (a private survey has none: it uses personal links). Your system sends the link the way it already reaches people. Pass your own id in a web link as a hidden field and match it when the response comes back.

// Send the survey link from your own system (email, SMS, an HR portal).
const res = await fetch(`https://www.surveyr.africa/api/external/v2/surveys/${SURVEY_ID}/links`, { headers: { "x-api-key": process.env.SURVEYR_API_KEY } });
const { data } = await res.json();

for (const person of newStarters) {
  // Web link: hidden fields come back on the response as hiddenFields (up to 10 keys of a–z, 0–9, _).
  const web = data.web && `${data.web.url}?hf_employee_id=${encodeURIComponent(person.id)}`;
  await mailer.send(person.email, "Two minutes for your onboarding survey?", web ?? data.whatsapp.url);
}
// Then listen for response.completed and match record.hiddenFields.employee_id to the person.

Sending the survey over WhatsApp from Surveyr itself, with per-person delivery states (queued, sent, delivered, read, failed, responded), is coming as the Distributions API. It will respect opt-in, template approval and WhatsApp's 24-hour window.

Recipe 3

Nightly export to your warehouse

  • Each night, pull GET /responses?updatedSince=<last run minus 10 minutes> and follow meta.nextCursor until meta.hasMore is false.
  • Upsert on id. Each version of a report is its own row; latest: true marks the current one and deleted: true a deletion notice.
  • For one survey as a file, GET /surveys/{id}/responses?format=csv (the next page's cursor is in the X-Next-Cursor header). It ends with a hidden_fields column, and a text cell that starts with =, +, -, @, a tab or a carriage return gets a leading ', so opening it in a spreadsheet can't run it as a formula (plain numbers such as -5 are left alone).
  • On 429, wait Retry-After seconds and carry on with the same cursor.
import os, time, requests

BASE = "https://www.surveyr.africa/api/external/v2"
HEADERS = {"x-api-key": os.environ["SURVEYR_API_KEY"]}

def nightly_export(last_run_iso: str):
    params = {"updatedSince": last_run_iso, "limit": 500}
    while True:
        r = requests.get(f"{BASE}/responses", headers=HEADERS, params=params, timeout=30)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "5"))); continue
        r.raise_for_status()
        body = r.json()
        warehouse.upsert(body["data"], key="id")   # every version; keep latest == True for the current one
        if not body["meta"]["hasMore"]:
            break
        params = {"cursor": body["meta"]["nextCursor"], "limit": 500}
Part 5

Usage, plans and the sandbox

  • GET /usage (and Settings → API) shows this month's requests by key and day, your quota and when it resets.
  • Test keys have their own small quota and are never billed. Live keys work on paid plans; on the free sandbox plan only test keys work.
  • If a payment is overdue, reads keep working and writes pause (402 payment_required). Nothing you stored is ever dropped.

Questions

Should I poll or use webhooks?

Webhooks for anything that should react quickly; a nightly updatedSince pull as a safety net. Both give the same record shape.

Can I call the API from a browser or mobile app?

No. A key reads personal information; keep it on your server.

Why do I get 404 for an id I know exists?

It belongs to another organisation, or your test key is looking for a live survey. Test keys only see sandbox data.

I use the v1 feed. Do I have to move?

No. v1 keeps working unchanged. Move when you want webhooks, scoped keys or the sandbox.