Foresight API Reference
Version: 1.0 | Base URL:
https://<your-domain>| Schema Version:1.0
Every endpoint, field, flag, and behavior of the Foresight REST API, so you can integrate without guessing.
The API is organized into five groups:
| Group | What it does | Typical use |
|---|---|---|
| Import | High-volume upsert of leads, single row or batch | List providers, nightly syncs, scrapers |
| Leads | Read, search, update, assign, archive, export, plus campaign control: tags, seller path, foreclosure stage, cadence enrollment, per-number DNC, skip trace | Reporting, dashboards, two-way sync, keeping outreach in step with what your own system knows |
| Calls | Read human dialer, AI caller, and AI receptionist call records in one shape | Call reporting and synchronization |
| Foreclosure | Auction dates, upset bids, watchlists | County data automation |
| Webhooks | Token-authenticated lead intake, no API key needed | Zapier, Make, PPC landing pages, Facebook Lead Ads |
Table of Contents
- Quick Start
- Authentication
- Scopes
- Rate Limits
- Supported Fields
- Flags
- Matching Logic
- Hash Behavior (Skip-if-Unchanged)
- Idempotency
- Import Endpoints
- Lead Endpoints
- Call Endpoints
- Contact Endpoints
- Document Endpoints
- Foreclosure Endpoints
- Stats Endpoints
- Inbound Webhooks
- Error Codes
- Per-Row Result Actions
Quick Start
1. Create an API Key
In the application UI go to Settings → API Keys → Create Key.
- Name: give it a descriptive name (e.g.
automation-upload). - Permissions: select
import:run. - The UI will show the raw key once — copy it immediately. It looks like
pfp_<64-hex-chars>.
2. Verify connectivity
curl -s https://<your-domain>/api/v1/health | python3 -m json.tool
Expected:
{
"status": "ok",
"version": "1.0.0",
"database": "connected",
"timestamp": "2026-03-25T12:00:00.000Z"
}
3. Import your first lead
curl -X POST https://<your-domain>/api/v1/import/lead \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: test-001" \
-d '{
"address": "123 Main St",
"city": "Columbus",
"state": "OH",
"zip": "43215",
"firstName": "Jane",
"lastName": "Doe",
"phone": "6145551234",
"source": "automation"
}'
Expected response (201 created or 200 updated):
{
"success": true,
"action": "created",
"leadId": "uuid-...",
"propertyId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": null,
"duration_ms": 42
}
Authentication
Every endpoint requires a Bearer token in the Authorization header, with one exception: inbound webhooks authenticate with a token in the URL instead.
Authorization: Bearer pfp_<key>
- Keys are created in the UI under Settings → API Keys.
- The key prefix (
pfp_) is required. - Keys can be revoked (deleted) from the same UI page.
- Every request is scoped to the organization that owns the key. A key can never read or write another organization's data.
Key Format
| Part | Example | Description |
|---|---|---|
| Prefix | pfp_ | Fixed literal prefix |
| Key body | a1b2c3d4... | 64 hex characters |
Rate Limit per Key
When creating a key, you can optionally set a custom rateLimit. If not set:
- Keys with
import:*orautomationpermissions default to 600 req/min. - All other keys default to 100 req/min.
Scopes
Read-only keys
Tick "Read-only (GET requests only)" when generating a key to store read_only in its permissions. Only GET requests are allowed; POST, PUT, PATCH, DELETE and HEAD return 403 with code READ_ONLY_KEY. MCP uses POST and is blocked too. Resource scopes still apply. A key holding only read_only has all read scopes. Existing keys retain their behavior. This flag does not count as an automation permission for rate limits.
Each endpoint requires a specific permission scope, selected when the key is created.
| Scope | Grants access to |
|---|---|
import:run | All /api/v1/import/* endpoints |
leads:create | POST /api/v1/leads |
leads:read | GET /api/v1/leads, /leads/:leadId, /leads/search, /leads/export, /users, /users/:userId, /settings/lead-tiers, /settings/outreach-gate, /foreclosure/lookup, /foreclosure/watchlist, GET /leads/:leadId/notes |
leads:update | PATCH /api/v1/leads/:leadId, DELETE /api/v1/leads/:leadId, /leads/bulk-update, POST /leads/:leadId/notes, PATCH/DELETE /leads/:leadId/notes/:noteId, /leads/:leadId/tags, /leads/:leadId/seller-path, /leads/:leadId/foreclosure-stage, /leads/:leadId/cadence-enroll, /leads/:leadId/cadence-pause, /leads/:leadId/cadence-cancel, /leads/:leadId/cadence-resume, /leads/:leadId/skip-trace |
leads:assign | POST /api/v1/leads/:leadId/assign |
messages:read | GET /api/v1/messages, GET /api/v1/leads/:leadId/messages, GET /api/v1/leads/:leadId/emails |
calls:read | GET /api/v1/calls, GET /api/v1/calls/:callId, GET /api/v1/leads/:leadId/calls |
contacts:update | /leads/:leadId/phones, /leads/:leadId/emails, /leads/:leadId/phone-dnc, PATCH /api/v1/contacts/:contactId |
documents:upload | POST /api/v1/leads/:leadId/documents |
documents:read | GET /api/v1/leads/:leadId/documents |
foreclosure:update | /foreclosure/update-auction, /foreclosure/update-upset-bid |
stats:read | GET /api/v1/stats/leads |
reports:read | GET /api/v1/reports/activity |
Calling an endpoint without its scope returns 403:
{
"success": false,
"message": "Missing required scope: leads:read"
}
Important: a key created with no scopes selected is treated as unrestricted and can call every endpoint. Always select the narrowest set of scopes your integration needs.
Additional permission checks
The document endpoints also require the key's owning user to hold the api:upload_documents permission, which is managed under Settings → Roles. This applies to both uploading and listing documents. Without it both endpoints return 403 regardless of the key's scopes.
County Data trial restriction
If your organization is on a County Data trial and has received delivered county leads, the bulk read endpoints (GET /leads, /leads/search, /leads/export) are blocked until the trial converts to a paid plan:
{
"success": false,
"message": "County Data trial leads cannot be exported until the trial converts",
"code": "COUNTY_TRIAL_EXPORT_BLOCKED"
}
HTTP status: 403. Normal in-app use is unaffected; only extraction surfaces invoke this guard.
Rate Limits
Rate limiting is applied per API key on a sliding 60-second window.
| Header | Description |
|---|---|
X-RateLimit-Limit | Max requests allowed per minute |
X-RateLimit-Remaining | Requests remaining in the current window |
X-RateLimit-Reset | Unix timestamp (seconds) when the window resets |
When the limit is exceeded the API returns:
{
"success": false,
"error_code": "RATE_LIMIT_EXCEEDED",
"message": "Rate limit exceeded. 600 requests per minute allowed."
}
HTTP status: 429
Requests in progress. Separately from the per-minute count, the API limits how many requests run at once. By default each API key runs at most 2 requests at once, and up to 20 more of that key's requests wait for one of its slots. A request that holds a key slot then needs one of the platform's slots, which all keys share (4 by default, and never more than a quarter of the database connections), and up to 100 such requests wait for one by default. A deployment can configure each of these numbers. A waiting request does not hold a database connection for its handler. Its key lookup is finished before it waits, but that key's "last used" update (at most once a minute) can still be running. A request that cannot wait gets 429 with a Retry-After: 2 header, and it does not count against the per-minute limit:
{
"success": false,
"error_code": "CONCURRENCY_LIMIT_EXCEEDED",
"message": "Too many API requests in progress. Retry after 2 seconds."
}
Send one or two requests at a time per key, and wait at least the Retry-After seconds before retrying.
Supported Fields
Fields are grouped by entity. All fields are optional — the minimum useful import is an address (or external_id).
Contact Fields
| Field | Type | Aliases | Notes |
|---|---|---|---|
firstName | string | — | |
lastName | string | — | |
fullName | string | — | Parsed into first/last if provided alone |
phone | string | phonePrimary | Primary phone |
email | string | emailPrimary | Primary email |
mailingAddress | string | — | Owner mailing address |
Property Fields
| Field | Type | Aliases | Notes |
|---|---|---|---|
address | string | street | Street address |
city | string | — | |
state | string | — | 2-letter code preferred |
zip | string / number | — | |
county | string | — | |
parcelId | string | — | |
externalId | string | external_id | Your unique ID for this property |
propertyType | string | — | |
yearBuilt | integer | — | |
beds | integer | — | |
baths | number | — | Accepts decimals (e.g. 2.5) |
sqft | integer | — | |
lotSize | string | — | |
zestimate | number | — | Zillow estimate |
zrent | number | — | Zillow rent estimate |
zillowUrl | string | zillow_url | Listing URL. Participates in the change hash, so editing it alone is enough to make skip_if_same treat the row as changed |
annualTax | number | — |
Lead Fields
| Field | Type | Notes |
|---|---|---|
status | enum | See values below |
source | string | Freeform label (default "automation") |
distressType | string | |
notes | string |
Status values: prospect, lead, opportunity, appointment_set, offer_made, under_contract, closing, closed, closed_won, closed_rental, dead, redemption_period
Foreclosure Fields
| Field | Type | Aliases |
|---|---|---|
caseNumber | string | case_number |
spNumber | string | sp_number |
auctionDate | date (ISO string) | auction_date |
recordDate | date (ISO string) | record_date. Native NOTICE DATE on the Foreclosure Intelligence card. Calendar day only; omitted rows are unchanged, JSON null clears. |
attorney | string | — |
mortgagee | string | — |
openingBid | number | opening_bid |
estLoanBalance | number | est_loan_balance |
estEquity | number | est_equity |
Flags
Flags modify import behavior. Pass them as top-level boolean fields in the request body (or as query parameters for batch).
| Flag | Default | Description |
|---|---|---|
strict | false | Batch-only. Wraps all rows in a DB transaction — if any row fails the entire batch is rolled back. |
update_only | false | Only update existing records; never create new ones. Single-row endpoints return 404 with error_code: "NOT_FOUND". In batch jobs, rows return action: "not_found". |
create_only | false | Only create new records; never update existing ones. Rows that match return already_exists. |
overwrite_empty | false | When false (default), incoming empty/null values are ignored and existing data is preserved. When true, empty values overwrite existing data. |
overwrite_all | false | Same behavior as overwrite_empty — allows empty incoming values to overwrite existing data. Mutually exclusive with overwrite_empty (setting both returns INVALID_FLAGS). |
skip_if_same | true | When true (default), rows whose computed import hash matches the stored hash are skipped (action: "skipped"). Set to false to force re-processing even if the hash matches, including an exact repeat of a batch that already succeeded today. |
dry_run | false | Simulate the import without writing anything. The response shows what would happen. Pass as query ?dry_run=true or body field. |
preserve_verified_fields | false (true for source: "automation") | Fields a user has confirmed in the CRM are left alone, even when the incoming row has a different value. Recommended for any recurring vendor sync. |
force_reassign | false | Allow the import to reassign an already-owned lead. Off by default so a sync never moves a rep's lead out from under them. |
allow_automated_outreach | true | Set false to import without starting outreach: records are written as normal, but newly created leads are not enrolled into a cadence. See below. |
allow_auto_enrich | true | Set false to import without spending your enrichment allowance: no DealMachine / ATTOM skip trace is queued for the property. See below. |
Constraints:
update_onlyandcreate_onlyare mutually exclusive — setting both returnsINVALID_FLAGS.overwrite_allandoverwrite_emptyare mutually exclusive — setting both returnsINVALID_FLAGS.
Silent Imports
By default, a lead created through the API is treated like an inbound lead: if it arrives with a phone or email it is auto-enrolled into a cadence, and if it arrives without one the property is queued for a DealMachine / ATTOM skip trace that meters against your enrichment allowance. That is right for a speed-to-lead webhook and wrong for a bulk vendor sync.
Two independent flags turn those off:
| Flag | false means |
|---|---|
allow_automated_outreach | Do not enroll newly created leads into a cadence. Nothing texts or emails on its own. |
allow_auto_enrich | Do not queue a billable skip trace. Use this when your pipeline already enriched the records before pushing them. |
They are separate on purpose. A cold list can be worth skip-tracing so a rep can work it by hand without anything texting it, and a list you already enriched elsewhere should not be paid for twice even if you do want outreach.
curl -X POST https://<your-domain>/api/v1/import/leads \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"source": "propertyradar",
"create_only": true,
"allow_automated_outreach": false,
"allow_auto_enrich": false,
"leads": [ { "external_id": "pr:12345678", "address": "123 Main St", "city": "Columbus", "state": "OH", "zip": "43215" } ]
}'
What changes:
| Behavior | Flags omitted | Both false |
|---|---|---|
| Property / contact / lead writes | Yes | Yes (unchanged) |
| Cadence auto-enrollment on newly created leads | Yes | No |
| DealMachine / ATTOM auto-enrichment | Yes | No |
| Retroactive nightly enrollment sweeps | Lead is eligible | Lead stays excluded |
Notes:
- Supported on
POST /api/v1/import/lead,POST /api/v1/import/leads(sync and async), andPOST /api/v1/leads. Both are also accepted as query parameters and in camelCase (allowAutomatedOutreach,allowAutoEnrich). - Outreach suppression is durable. Leads created with
allow_automated_outreach: falseare stamped with a marker import batch, so the nightly sweeps that enroll unenrolled foreclosure leads skip them permanently. Without that stamp a silent import would start texting the next night. - Suppressing outreach while leaving enrichment on is safe: the skip trace runs, but the enrollment that normally follows it does not.
- Both apply to leads this call creates. Leads that already exist and are merely updated keep whatever enrollment they already had.
- To start outreach later, enroll from the UI (select the leads and start a cadence) or re-import without the flag. Re-importing does not retroactively enroll the leads created while it was set.
- An import source can be configured to hold outreach or enrichment by default.
When it is, that setting wins even if a request sends
true.
Matching Logic
When a row is imported the system tries to find an existing property to update. Matches are attempted in priority order — the first match wins:
| Priority | Key(s) | Description |
|---|---|---|
| 1 | external_id | Exact match on your external identifier within the organization |
| 2 | case_number + county | Foreclosure case match |
| 3 | address + city + state + zip | Full normalized-address match |
| 4 | address (street only) | Fuzzy street-only fallback |
| 5 | phone + lastName | Contact-based match (requires phone ≥ 10 digits and last name) |
If no match is found, a new property + lead + contact is created (unless update_only is set).
The response includes a matchedBy field indicating which key matched: "external_id", "case_number", "address", "address_street", "phone_name", or null (new record).
Hash Behavior (Skip-if-Unchanged)
Every imported row is hashed using a SHA-256 digest of key fields:
address, city, state, zip, county, firstName, lastName, phone,
caseNumber, auctionDate, openingBid, beds, baths, sqft, yearBuilt,
propertyType, zestimate, lotSize, overwrite_empty
- Values are lowercased and trimmed before hashing.
- When
skip_if_sameistrue(the default), if the computed hash matches the storedimportHashon the existing property, the row is skipped withaction: "skipped"— no database writes occur. - Set
skip_if_same: falseto force re-processing even if the hash matches. OnPOST /api/v1/import/leads,falsealso bypasses the daily payload ledger (skipped_duplicate_file), so a retried batch of the same bytes actually runs. - The hash is stored on the property record as
importHashafter each successful import.
This means re-importing the same file is safe and fast — unchanged rows are automatically skipped.
Idempotency
To prevent duplicate processing on retries, send an Idempotency-Key header with a unique value per logical request.
Idempotency-Key: upload-2026-03-25-batch-001
Behavior
- The key is scoped to your API key, HTTP method, and path.
- If a request with the same key has already completed, the original response is replayed with
"idempotent_replay": true. - If a request with the same key is currently processing, you receive
409witherror_code: "IN_PROGRESS". - Idempotency records expire after 24 hours.
Batch Idempotency
For the batch endpoint (POST /api/v1/import/leads), idempotency also covers async jobs:
- Sync batches: stored under key
sync-batch:<apiKeyId>:<your-key>. - Async jobs: stored as
batch:<apiKeyId>:<your-key>in the job record. If a duplicate is submitted, the existingjob_idis returned with"duplicate": true.
Import Endpoints
Health Check
Check API and database connectivity.
GET /api/v1/health
No authentication required.
curl https://<your-domain>/api/v1/health
Response (200):
{
"status": "ok",
"version": "1.0.0",
"database": "connected",
"timestamp": "2026-03-25T12:00:00.000Z"
}
Verify Key
Confirms a key is valid and shows exactly what it can do. Use this first when debugging a 403.
GET /api/v1/auth/verify
curl https://<your-domain>/api/v1/auth/verify \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE"
Response (200):
{
"success": true,
"message": "API key is valid",
"apiKeyId": "uuid-...",
"userId": "uuid-...",
"organizationId": "uuid-...",
"organizationName": "Acme Acquisitions",
"permissions": ["leads:read", "leads:update"],
"unrestricted": false,
"readOnly": false,
"availableScopes": ["leads:read", "leads:create", "leads:update", "leads:assign", "contacts:update", "calls:read", "messages:read", "foreclosure:update", "stats:read", "reports:read", "import:run", "documents:upload", "documents:read"],
"key": {
"id": "uuid-...",
"name": "Agent team",
"keyPrefix": "1234abcd",
"createdAt": "2026-10-01T12:00:00.000Z",
"lastUsedAt": "2026-11-05T15:04:05.000Z",
"createdBy": { "id": "uuid-...", "name": "API Owner", "email": "owner@example.com" }
}
}
An empty permissions array means the key is unrestricted and can call every endpoint, which is also reported as unrestricted: true. unrestricted ignores read_only; readOnly reports that flag separately. availableScopes is the complete current scope list. key.lastUsedAt is the key's last use before this request, so it is null on a new key's first call. key.createdBy is null for a key with no creator; its name and email are null if the creator no longer belongs to this organization. The key hash is never returned. See Scopes.
Schema / Field List
Returns all supported import fields with types and grouping.
GET /api/v1/schema/leads
Auth: Bearer token required.
curl https://<your-domain>/api/v1/schema/leads \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response (200):
{
"success": true,
"fields": [
{ "name": "firstName", "type": "string", "group": "contact" },
{ "name": "address", "type": "string", "group": "property" },
...
]
}
Import Config
Returns server-side limits, supported flags, and current queue state.
GET /api/v1/import/config
Auth: Bearer token required.
curl https://<your-domain>/api/v1/import/config \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response (200):
{
"max_batch_size": 5000,
"max_sync_batch_size": 50,
"max_file_size_mb": 25,
"max_concurrent_jobs": 3,
"max_job_attempts": 3,
"supported_schema_versions": ["1.0"],
"current_schema_version": "1.0",
"supported_sources": ["automation", "ui", "system"],
"supported_flags": ["strict", "update_only", "create_only", "overwrite_empty", "overwrite_all", "skip_if_same", "dry_run"],
"matching_keys": ["external_id", "case_number+county", "address+city+state+zip"],
"active_jobs": 0,
"rate_limit": 600,
"server_time": "2026-03-25T12:00:00.000Z"
}
Import Stats
Returns today's import statistics for your organization.
GET /api/v1/import/stats
Auth: Bearer token + import:run scope.
curl https://<your-domain>/api/v1/import/stats \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response (200):
{
"success": true,
"counts": {
"today_imports": 12,
"total_rows_processed": 450,
"created": 200,
"updated": 150,
"skipped": 90,
"failed": 10,
"active_jobs": 0,
"queue_depth": 0
},
"performance": {
"avg_row_time_ms": 8,
"avg_job_duration_ms": 4500,
"p95_row_time_ms": 15,
"queue_latency_ms": 200,
"estimated_processing_ratio": 0.96
},
"health": {
"failed_job_count": 0,
"retry_pending_count": 0,
"stale_job_count": 0
}
}
Single-Row Upsert (POST)
Import or update a single lead/property/contact row.
POST /api/v1/import/lead
Auth: Bearer token + import:run scope.
Headers:
| Header | Required | Description |
|---|---|---|
Authorization | Yes | Bearer pfp_... |
Content-Type | Yes | application/json |
Idempotency-Key | Recommended | Unique string for retry safety |
Body: A JSON object with any combination of supported fields plus optional flags and metadata:
| Body Field | Type | Default | Description |
|---|---|---|---|
source | string | "automation" | Import source label |
schema_version | string | "1.0" | Schema version |
strict | boolean | false | (ignored for single row) |
update_only | boolean | false | |
create_only | boolean | false | |
overwrite_empty | boolean | false | |
overwrite_all | boolean | false | |
skip_if_same | boolean | true | Set false to force re-processing unchanged rows |
dry_run | boolean | false | Also accepted as query ?dry_run=true |
Example — create a new lead:
curl -X POST https://<your-domain>/api/v1/import/lead \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: row-abc-001" \
-d '{
"address": "456 Oak Ave",
"city": "Cleveland",
"state": "OH",
"zip": "44101",
"firstName": "John",
"lastName": "Smith",
"phone": "2165559876",
"caseNumber": "2026-CV-1234",
"county": "Cuyahoga",
"auctionDate": "2026-06-15",
"openingBid": 85000,
"source": "automation"
}'
Response (201 created):
{
"success": true,
"action": "created",
"leadId": "uuid-...",
"propertyId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": null,
"duration_ms": 38
}
Response (200 updated — same address re-imported with changes):
{
"success": true,
"action": "updated",
"leadId": "uuid-...",
"propertyId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": "address",
"duration_ms": 25
}
Response (200 skipped — hash unchanged):
{
"success": true,
"action": "skipped",
"leadId": "uuid-...",
"propertyId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": "address",
"duration_ms": 12
}
Dry-run example:
curl -X POST "https://<your-domain>/api/v1/import/lead?dry_run=true" \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{ "address": "789 Elm St", "city": "Akron", "state": "OH", "zip": "44301" }'
Single-Row Update-Only (PATCH)
Update an existing record without creating new ones. Behaves like POST /api/v1/import/lead with update_only: true forced.
PATCH /api/v1/import/lead
Auth: Bearer token + import:run scope.
curl -X PATCH https://<your-domain>/api/v1/import/lead \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: patch-abc-002" \
-d '{
"external_id": "prop-99",
"openingBid": 92000,
"auctionDate": "2026-07-01"
}'
Response (200 updated):
{
"success": true,
"action": "updated",
"leadId": "uuid-...",
"propertyId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": "external_id",
"duration_ms": 20
}
Response (404 not found — no matching record):
{
"success": false,
"error_code": "NOT_FOUND",
"message": "No matching property found for update",
"duration_ms": 8
}
Lookup
Check whether a property already exists without modifying anything.
GET /api/v1/import/lookup
Auth: Bearer token + import:run scope.
Query parameters (at least one group is required):
| Group | Parameters |
|---|---|
| External ID | external_id |
| Full address | address + city + state + zip |
| Case number | case_number + county |
curl "https://<your-domain>/api/v1/import/lookup?address=123+Main+St&city=Columbus&state=OH&zip=43215" \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response — found (200):
{
"success": true,
"found": true,
"propertyId": "uuid-...",
"leadId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": "address",
"importHash": "sha256-hex...",
"lastImportAt": "2026-03-24T18:00:00.000Z",
"lastImportSource": "automation",
"externalId": "prop-42",
"duration_ms": 6
}
Response — not found (200):
{
"success": true,
"found": false,
"duration_ms": 4
}
Batch Import
Import multiple rows at once. Small batches (≤ 50 rows by default) are processed synchronously; larger batches are queued as async jobs.
POST /api/v1/import/leads
Auth: Bearer token + import:run scope.
Input Formats
The endpoint accepts three formats:
- JSON array —
Content-Type: application/json, body is[ {row1}, {row2}, ... ] - JSON object with
leadskey —Content-Type: application/json, body is{ "leads": [...], "source": "...", ... } - CSV file upload —
Content-Type: multipart/form-data, field namefile
Limits
| Limit | Default | Env Var |
|---|---|---|
| Max batch size | 5,000 rows | IMPORT_MAX_BATCH_SIZE |
| Sync threshold | 50 rows | IMPORT_MAX_SYNC_BATCH_SIZE |
| Max file size | 25 MB | IMPORT_MAX_FILE_SIZE_MB |
| Max concurrent async jobs | 3 | IMPORT_MAX_CONCURRENT_JOBS |
| Max job retry attempts | 3 | IMPORT_MAX_JOB_ATTEMPTS |
Flags & Metadata
Pass as body fields (JSON object format) or query parameters:
source(string)schema_version(string)strict(boolean)update_only(boolean)create_only(boolean)overwrite_empty(boolean)overwrite_all(boolean)skip_if_same(boolean, defaulttrue)dry_run(boolean)idempotency_key(string) — alternative to theIdempotency-Keyheader
Example — JSON array (sync, ≤ 50 rows)
curl -X POST https://<your-domain>/api/v1/import/leads \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: batch-2026-03-25-001" \
-d '[
{ "address": "100 First St", "city": "Columbus", "state": "OH", "zip": "43215", "firstName": "Alice", "lastName": "Jones" },
{ "address": "200 Second St", "city": "Columbus", "state": "OH", "zip": "43215", "firstName": "Bob", "lastName": "Brown" }
]'
Sync response (200):
{
"success": true,
"mode": "sync",
"status": "completed",
"summary": {
"total": 2,
"created": 2,
"updated": 0,
"skipped": 0,
"failed": 0
},
"results": [
{ "row": 0, "success": true, "action": "created", "leadId": "uuid-...", "propertyId": "uuid-..." },
{ "row": 1, "success": true, "action": "created", "leadId": "uuid-...", "propertyId": "uuid-..." }
],
"duration_ms": 120
}
Example — CSV file upload (async, > 50 rows)
curl -X POST https://<your-domain>/api/v1/import/leads \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Idempotency-Key: csv-upload-001" \
-F "file=@leads.csv" \
-F "source=automation"
Async response (202):
{
"success": true,
"mode": "async",
"job_id": "uuid-...",
"status": "queued",
"total_rows": 1200,
"status_url": "/api/v1/import/status/uuid-...",
"result_url": "/api/v1/import/result/uuid-...",
"duration_ms": 15
}
Example — JSON object with leads array
curl -X POST https://<your-domain>/api/v1/import/leads \
-H "Authorization: Bearer pfp_YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"source": "automation",
"update_only": true,
"leads": [
{ "external_id": "prop-1", "openingBid": 75000 },
{ "external_id": "prop-2", "openingBid": 110000 }
]
}'
Strict Mode
When strict: true, all rows are wrapped in a single database transaction. If any row fails, the entire batch is rolled back and the response includes error_code: "STRICT_ABORT".
Batch Deduplication
Within a single batch, rows are deduplicated by address+city+state+zip and phone. If a later row matches an earlier row in the same batch, it is marked already_exists with matchedBy: "batch_dedup" — no extra database lookup occurs.
Sync vs. Async Summary
| Criteria | Sync | Async |
|---|---|---|
| Row count | ≤ 50 | 51 – 5,000 |
| Response code | 200 | 202 |
| Results in response | Yes (up to 200 rows) | No — poll status/result endpoints |
| Idempotency | Via Idempotency-Key header or body | Via Idempotency-Key header or body |
Job Status
Poll the status of an async import job.
GET /api/v1/import/status/:jobId
Auth: Bearer token + import:run scope.
curl https://<your-domain>/api/v1/import/status/JOB_ID \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response (200):
{
"success": true,
"job_id": "uuid-...",
"status": "processing",
"total_rows": 1200,
"processed_rows": 450,
"summary": {
"created": 300,
"updated": 100,
"skipped": 40,
"failed": 10
},
"attempt": 1,
"max_attempts": 3,
"next_retry_at": null,
"duration_ms": null,
"created_at": "2026-03-25T12:00:00.000Z",
"started_at": "2026-03-25T12:00:01.000Z",
"completed_at": null,
"error": null
}
Job statuses: queued, processing, completed, partial_failed, failed, retry_pending, permanently_failed
Job Result
Retrieve per-row results for a completed async job.
GET /api/v1/import/result/:jobId
Auth: Bearer token + import:run scope.
curl https://<your-domain>/api/v1/import/result/JOB_ID \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response — completed (200):
{
"success": true,
"job_id": "uuid-...",
"status": "completed",
"total_rows": 1200,
"summary": {
"created": 800,
"updated": 350,
"skipped": 45,
"failed": 5
},
"results": [
{ "row": 0, "success": true, "action": "created", "leadId": "uuid-...", "propertyId": "uuid-..." },
{ "row": 1, "success": true, "action": "updated", "leadId": "uuid-...", "propertyId": "uuid-...", "matchedBy": "address" }
],
"duration_ms": 45000
}
Response — still processing (200):
{
"success": true,
"job_id": "uuid-...",
"status": "processing",
"message": "Job is still processing",
"processed_rows": 450,
"total_rows": 1200
}
Job Row Results
Per-row outcomes for a finished batch job, as JSON or CSV. Use this when you need to reconcile which of your rows landed and why, rather than just the summary counts.
GET /api/v1/import/jobs/:jobId/results
Scope: import:run
| Query param | Default | Notes |
|---|---|---|
format | json | Set to csv for a downloadable file |
curl "https://<your-domain>/api/v1/import/jobs/JOB_ID/results?format=csv" \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-o import-results.csv
Response (200):
{
"success": true,
"job_id": "uuid-...",
"status": "completed",
"total_rows": 1200,
"summary": { "created": 900, "updated": 250, "skipped": 40, "failed": 10 },
"rows": [
{ "rowIndex": 0, "action": "created", "success": true, "leadId": "uuid-...", "matchedBy": null }
]
}
CSV columns: row_index, action, success, lead_id, property_id, contact_id, matched_by, changed_fields, error_code, error_message.
Response — still running (202):
{ "success": true, "job_id": "uuid-...", "status": "processing", "message": "Job is still processing" }
Returns 404 if the job does not exist or belongs to another organization.
Legacy Batch Lookup
Retrieve summary information for a legacy import batch by its ID.
GET /api/v1/import/:importId
Auth: Bearer token + import:run scope.
curl https://<your-domain>/api/v1/import/IMPORT_BATCH_ID \
-H "Authorization: Bearer pfp_YOUR_KEY"
Response (200):
{
"success": true,
"id": "uuid-...",
"status": "completed",
"totalRows": 500,
"processed": 500,
"created": 400,
"duplicates": 80,
"failed": 20,
"fileName": "leads.csv",
"createdAt": "2026-03-24T10:00:00.000Z"
}
Response (404 — not found):
{
"success": false,
"message": "Import batch not found"
}
Lead Endpoints
These endpoints operate on individual leads that already exist in the CRM, or create them one at a time. For high-volume ingest use the import endpoints instead.
Create Lead
POST /api/v1/leads · Scope: leads:create
Creates a property, contact, and lead in one call. Unlike POST /api/v1/import/lead, this endpoint refuses duplicates rather than updating them.
Request
curl -X POST https://<your-domain>/api/v1/leads \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: create-001" \
-d '{
"firstName": "Jane",
"lastName": "Doe",
"phone": "6145551234",
"email": "jane@example.com",
"address": "123 Main St",
"city": "Columbus",
"state": "OH",
"zip": "43215",
"status": "prospect",
"source": "zapier"
}'
Body fields
| Field | Type | Notes |
|---|---|---|
firstName / lastName / fullName | string | At least one is required. fullName is split on the first space when the parts are absent. |
phone, email | string | Primary contact channels |
phones, emails | array | Additional channels beyond the primary |
mailingAddress | string | Defaults to the property address |
address, street, city, state, zip, county, parcelId | string | Property location |
propertyType, yearBuilt, beds, baths, sqft, lotSize | mixed | Property characteristics |
zestimate, zrent, annualTax | number | Valuation |
status | enum | Defaults to prospect. See Supported Fields for the full list. |
source | string | Defaults to api. Use something identifiable per integration. |
tags, distressType | array / string | Applied as lead tags |
notes | string | Free text |
isDeceased, age | boolean / integer | Contact attributes, written on create only |
externalId | string | Your system's ID, retained for tag provenance |
auctionDate, recordDate, caseNumber, attorney, mortgagee, estLoanBalance, estEquity, openingBid, noticeUrl, saleStatus, noticeFamily | mixed | Foreclosure data. Supplying auctionDate, recordDate, or caseNumber creates a foreclosure record; caseNumber also creates an auction tracking row. recordDate is the native NOTICE DATE; a date-only write does not change auction dates, contacts, holds, or campaigns. |
allow_automated_outreach | boolean | Defaults to true. See Silent Imports. |
allow_auto_enrich | boolean | Defaults to true. Controls billable skip trace. |
Response 201
{
"success": true,
"leadId": "uuid-...",
"contactId": "uuid-...",
"propertyId": "uuid-..."
}
Duplicate 409 — a lead already exists at this address:
{
"success": false,
"message": "Duplicate lead found at this address",
"existingLeadId": "uuid-..."
}
Notes
- Supports the
Idempotency-Keyheader. See Idempotency. - A
yearBuiltbefore 1978 automatically sets the lead-paint flag. - Cadence enrollment and skip trace run after the response is sent, so a
201does not mean outreach has started yet.
Get Lead
GET /api/v1/leads/:leadId · Scope: leads:read
The full record for one lead: the lead itself, its contact, its property, its foreclosure row, its auction tracking, and its cadence enrollments. Use this rather than filtering List Leads when you have an ID.
lead carries lastTouchAt and lastHumanTouchAt; see Touch and human touch.
The response also includes top-level customFields, for example {"custom_ltv":61.5}, or {} when no custom fields exist. assignedUser names the assignee when that user belongs to the organization, reports inOrganization: false with null personal fields for a stale outside user ID, and is null when unassigned. pulse is the score computed at response time, including the grade, six percentage scores, configured weights, completeness counts, missing critical fields, and computedAt. pillars contains the stored intake facts behind that score, such as askingPrice, mortgageBalance and monthsBehind; the Pulse Score section lists every field. It is null when this organization has no pillars row. When a foreclosure section exists it includes ltvRatio, for example "foreclosure": { "ltvRatio": 61.5, ... }; the value is null when unset. The foreclosure section remains null when no foreclosure row exists.
foreclosure.recordDateSource is the winning observation source for Notice Date (manual, import, niche, county, and so on), or null when no winner exists. foreclosure.recordDateLocked is true when that source outranks an API/import write (manual and vendor evidence). A hand-typed value or a hand-typed clear both lock the field; clearing the date on the card does not hand it back to the API. There is no unlock endpoint: type the date you want on the card, or skip locked records by reading this flag before you write. An import or PATCH that cannot move the field reports it on notProjected instead of updated / changed_fields.
curl -s https://<your-domain>/api/v1/leads/LEAD_ID \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE"
Response 200
{
"success": true,
"lead": {
"id": "uuid-...",
"status": "lead",
"source": "county-scraper",
"displayName": "Jane Doe",
"interestLevel": null,
"notes": "Owner called back",
"tags": ["foreclosure", "absentee"],
"distressType": "foreclosure",
"deadReason": null,
"deadNotes": null,
"doNotMail": false,
"doNotMailReason": null,
"doNotMailAt": null,
"sellerPath": "reinstating",
"sellerPathChangedAt": "2026-09-01T14:02:00.000Z",
"assignedTo": "uuid-...",
"isArchived": false,
"isMerged": false,
"mergedIntoId": null,
"createdAt": "2026-08-02T10:00:00.000Z",
"updatedAt": "2026-09-01T14:02:00.000Z",
"statusChangedAt": "2026-08-19T09:11:00.000Z"
},
"contact": {
"id": "uuid-...",
"firstName": "Jane",
"lastName": "Doe",
"fullName": "Jane Doe",
"phonePrimary": "6145551234",
"additionalPhones": ["6145559876"],
"phones": [
{
"phone": "6145551234",
"sms": { "suppressed": true, "optOutHold": true, "platformHold": false },
"voice": { "suppressed": false, "optOutHold": false, "platformHold": false }
},
{
"phone": "6145559876",
"sms": { "suppressed": false, "optOutHold": false, "platformHold": false },
"voice": { "suppressed": false, "optOutHold": false, "platformHold": false }
}
],
"emailPrimary": "jane@example.com",
"additionalEmails": [],
"mailingAddress": "PO Box 4, Columbus OH 43215",
"isDeceased": false,
"dncSms": false,
"dncVoice": false,
"lineType": "mobile",
"phoneStatus": "valid"
},
"property": {
"id": "uuid-...",
"address": "123 Main St",
"street": "123 Main St",
"city": "Columbus",
"state": "OH",
"zip": "43215",
"county": "Franklin",
"parcelId": "010-123456",
"yearBuilt": 1962,
"beds": 3,
"baths": 1.5,
"sqft": 1420,
"zestimate": 218000,
"zrent": 1750,
"zillowUrl": "https://www.zillow.com/homedetails/...",
"isAbsentee": true,
"propertyType": "single_family"
},
"foreclosure": {
"caseNumber": "24-CV-001234",
"auctionDate": "2026-11-04",
"recordDate": "2026-09-10",
"recordDateSource": "import",
"recordDateLocked": false,
"foreclosureStage": "auction_set",
"estLoanBalance": 154000,
"estEquity": 64000,
"saleStatus": "scheduled",
"noticeUrl": "https://county.example.gov/notice/..."
},
"auction": {
"auctionDate": "2026-11-04",
"auctionStatus": "scheduled",
"openingBid": 142000,
"upsetBid": null,
"upsetCount": 0,
"county": "Franklin",
"caseNumber": "24-CV-001234"
},
"cadences": [
{
"enrollmentId": "uuid-...",
"cadenceId": "uuid-...",
"cadenceName": "Gold Seller Outreach",
"source": "api_v1",
"status": "active",
"reference": "your-system-id",
"enrolledAt": "2026-09-10T14:02:11.000Z",
"lastStepAt": "2026-09-11T15:00:00.000Z",
"currentStep": 2,
"currentStepChannel": "sms",
"currentStepAmbiguous": false,
"nextStepAt": "2026-09-12T15:00:00.000Z",
"pausedAt": null,
"pausedReason": null,
"cancelledAt": null,
"cancelledReason": null,
"auctionDate": null
}
],
"cadencesTruncated": false
}
cadences and cadencesTruncated are always present. cadences is newest first (entries with no stored enrollment date come last), contains at most 200 entries, and contains every stored status including legacy responded and failed. cadencesTruncated is true when more entries exist. Each entry has enrollmentId, cadenceId, cadenceName, source (nullable), status, reference (nullable), enrolledAt (nullable on legacy rows), lastStepAt (nullable), currentStep, currentStepChannel (nullable), currentStepAmbiguous, nextStepAt (nullable), pausedAt (nullable), pausedReason (nullable), cancelledAt (nullable), cancelledReason (nullable), and auctionDate (nullable). Timestamps use the response's normal ISO timestamp format. auctionDate is YYYY-MM-DD only on an active or paused pre-sale foreclosure cadence with a pacing deadline; it is the lead's current pacing date, so finished entries carry null. currentStepChannel is null and currentStepAmbiguous is true when the cadence has more than one visible step at its current number.
cadences field | Nullable | Meaning |
|---|---|---|
enrollmentId, cadenceId, cadenceName, status, currentStep, currentStepAmbiguous, enrolledAt | no | Stored enrollment and cadence identity |
source, reference, lastStepAt, currentStepChannel, nextStepAt, pausedAt, pausedReason, cancelledAt, cancelledReason, auctionDate | yes | Stored lifecycle detail, or the countdown pacing date |
Notes
contact.phonesis the per-number suppression truth, and it is not the same thing asdncSms/dncVoice. Those two are contact-wide flags a rep can toggle. Thephonesarray reports each individual number, per channel:suppressed: nothing will send to this number on this channel right now.optOutHold: the consumer opted out, usually by replying STOP. Only an admin can release it, and only after the contact re-consents. See Per-Number DNC.platformHold: a compliance hold (litigator or DNC registry match, or a platform-level block). Nothing in the API or the UI can clear it.
- A contact can have
dncSms: falsewhile its primary number is suppressed. If you are deciding whether a number is safe to text, readphones, not the flags. contact,property,foreclosureandauctionare eachnullwhen the lead has no such record. Onlyleadis always present.
| Status | Meaning |
|---|---|
404 | Lead not found, or it belongs to another organization. The two are deliberately indistinguishable. |
List Leads
An unknown status, such as archived, returns 400 with { "success": false, "message": "Invalid status. Allowed: ..." }. The message lists every allowed status. Archiving is a separate flag, not a status value.
GET /api/v1/leads · Scope: leads:read
Touch and human touch
lastTouchAt and lastHumanTouchAt are camelCase fields on each lead, including both the plain list and include=pulse list. They are ISO UTC timestamps with microseconds, or null when no eligible touch exists. Get Lead puts them inside lead and computes them for the canonical surviving lead. List Leads computes them in one statement for the whole page.
A touch is an outbound text, email or call that the provider accepted, so it actually left Foresight. Exactly these rows count, each only when its lead is this org's lead and the row's organization_id is this org or null. Each channel requires its own provider evidence:
- Text (SMS and iMessage):
communicationswithtype = 'sms',direction = 'outbound',twilio_sid IS NOT NULL AND twilio_sid <> ''(Twilio SID or Sendblue handle),subtypenotai_shadow/ai_demo, andlower(delivery_status)notshadow/failed/undelivered/canceled. Exclude a terminally failed iMessage without an SMS resend:NOT EXISTS (SELECT 1 FROM imessage_outbound im WHERE im.handle = c.twilio_sid AND im.organization_id = orgId AND im.status IN ('held_unsafe','resend_failed')). The ledger is pinned to the key's organization.resent_sms(the same body went out over SMS) andokcount. A transiently failing ERROR resend staysqueued, is indistinguishable from one in flight, and counts until it settles. Time:COALESCE(sent_at, created_at). - Email:
communicationswithtype = 'email',direction = 'outbound',email_message_id IS NOT NULL AND email_message_id <> '', anddelivery_statusnotfailed/bounced/dropped, excluding syntheticcall-%message IDs. SendGriddroppedkeeps the provider ID but means the mail was discarded. Time:COALESCE(sent_at, created_at). - Dialer call:
call_logswithdirection = 'outbound',callee_call_sid IS NOT NULL AND callee_call_sid <> '' AND callee_call_sid NOT LIKE 'mobile-bridge:%', andstatus NOT IN ('failed','canceled'). The lead leg SID is the evidence.twilio_call_sidcan be only the rep's browser or cell leg even when the rep declines and the lead is never dialed.mobile-bridge:<sid>is a temporary claim. Calls logged by hand or imported from another CRM have no lead leg and do not count. Time:started_at. - AI call:
ai_callswithdirection = 'outbound',is_test_call = false,vapi_call_id IS NOT NULL AND vapi_call_id <> '',status NOT IN ('queued','failed','cancelled','canceled','skipped'), andoutcome IS DISTINCT FROM 'system_error'. A provider ID alone is insufficient when the accepted call then fails at start without dialing. Time:COALESCE(started_at, created_at).
Every exclusion on a nullable column is null-safe, so a row with null subtype, author, delivery_status or outcome stays eligible: IS DISTINCT FROM for single values, COALESCE(x, '') NOT IN (...) / COALESCE(x, '') NOT LIKE ... for lists and patterns. Accepted email can have a null delivery status.
Rows dated more than five minutes in the future are ignored. Not touches: notes and internal rows, anything inbound, call/voicemail/video_text/doorknock rows in communications, and texts sent inline as TwiML replies without a SID, including the opt-out acknowledgement. Dialer and AI calls are counted from their own tables.
A human touch is a touch a person sent by hand without AI drafting: a text or email touch with user_id set, is_ai not true, cadence_enrollment_id null, subtype not in (ai, ai_shadow, ai_demo, auto, sms_retention, appointment_reminder, missed_call_text_back, deliverability_check, rvm, migrated) and author not starting with system, case-insensitive; or a dialer call touch with user_id set. AI calls are never human touches. A person sending an AI-drafted text from the inbox is NOT a human touch: that row stores both user_id and is_ai = true (it is still a touch). The automated opt-out acknowledgement can store a person's user_id with subtype crm, but has no SID and is therefore not a touch.
| Query param | Default | Notes |
|---|---|---|
status | — | Exact match on lead status |
assignedUser | — | User ID |
county | none | Case-insensitive match, applied before pagination |
limit | 50 | Maximum 500 |
offset | 0 | Pagination offset |
tags | none | Comma list, any matching tag, normalized with the same rules as lead tags, maximum 20 |
exclude_tags | none | Comma list, exclude leads having any of these tags |
updated_after | none | Strictly newer lead update timestamp, ISO 8601 with timezone, invalid values return 400 |
created_after | none | Strictly newer lead creation timestamp, ISO 8601 with timezone, invalid values return 400 |
archived | include | include, exclude, or only; other values return 400 |
include | none | custom_fields adds customFields; pulse adds the computed Pulse Score and caps the page at 100 |
cadenceId | none | Only leads with an enrollment in this readable cadence |
cadenceStatus | none | Comma list of active, paused, completed, cancelled, responded, or failed. Requires cadenceId |
curl -s "https://<your-domain>/api/v1/leads?status=lead&limit=100" \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE"
Response 200
{
"success": true,
"leads": [
{
"id": "uuid-...",
"status": "lead",
"source": "zapier",
"displayName": "Jane Doe",
"assignedTo": "uuid-...",
"notes": null,
"contactId": "uuid-...",
"propertyId": "uuid-...",
"createdAt": "2026-03-25T12:00:00.000Z",
"firstName": "Jane",
"lastName": "Doe",
"phonePrimary": "6145551234",
"emailPrimary": "jane@example.com",
"address": "123 Main St",
"city": "Columbus",
"state": "OH",
"zip": "43215",
"county": "Franklin"
}
],
"total": 1,
"limit": 100,
"offset": 0,
"nextOffset": null
}
Archived leads are included by default. Merged duplicates are excluded. Every row has assignedUser with the same safe shape described by Get Lead. All filters combine with status, county, and assignedUser, and apply before pagination and the total count. Tag matching is scoped to the API key's organization. Empty or invalid tag lists return 400. cadenceStatus without cadenceId, or an invalid cadence status, returns 400. An unknown or inaccessible cadenceId returns an empty list and zero total.
nextOffset is offset + limit when the page contains limit rows, otherwise null. For example, a request with limit=100&offset=200 returning 40 rows has nextOffset: null. A full final page may still require one empty request to establish the end. Default list rows keep their existing fields; include=custom_fields adds, for example, "customFields": { "custom_ltv": 61.5 }. Include parsing is lenient: send one value, repeated values, or comma-separated values. Whitespace, blanks, and unknown tokens are ignored. A request carrying pulse uses a maximum limit of 100, and both limit and nextOffset report that effective cap.
Examples, each using GET /api/v1/leads with the Authorization header:
?tags=gold,silver
?exclude_tags=bronze
?updated_after=2026-09-08T12:00:00Z
?created_after=2026-09-01T00:00:00Z
?archived=only
?include=custom_fields
?include=pulse
?include=bogus,pulse&include=custom_fields
?tags=gold&exclude_tags=bronze&archived=exclude&status=lead&county=Franklin&assignedUser=USER_UUID
Agent integration tips: use updated_after for delta reads and follow nextOffset for paging. Use bulk-cadence instead of per-lead pause, cancel, and resume calls. To silence automatic drips without touching campaigns your own people started, send automatedOnly: true with the pause; a bulk pause with no filter stops every campaign on every lead you list. Read both counts a pause returns: enrollments is what stopped on the spot and pausingAfterCurrentStep is what will stop at its next safe point, and neither is meant to add up to the number of leads you sent. Store structured underwriting in custom-fields, and use tags for tiers. Custom-field merges update the lead's updatedAt, so they appear in delta reads.
Search Leads
GET /api/v1/leads/search · Scope: leads:read
Resolves an address or a foreclosure case number to an existing lead. Use this before creating a lead to avoid a 409.
| Query param | Notes |
|---|---|
caseNumber + county | Matched against auction tracking, then foreclosure records |
address (+ city, state, zip) | Matched against the property address, then the normalized address |
curl -s "https://<your-domain>/api/v1/leads/search?address=123%20Main%20St&city=Columbus&state=OH&zip=43215" \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE"
Found 200
{ "success": true, "found": true, "leadId": "uuid-...", "propertyId": "uuid-..." }
Not found 200
{ "success": true, "found": false }
Export Leads (CSV)
An unknown status, such as archived, returns 400 JSON with { "success": false, "message": "Invalid status. Allowed: ..." } instead of CSV. The message lists every allowed status.
GET /api/v1/leads/export · Scope: leads:read
Returns the matching result set as CSV, up to a ceiling of 25,000 rows. There is no pagination, so a matching set at or under the ceiling comes back in one file. Over it, the request returns 422 JSON and no CSV at all. A deployment can raise the ceiling, so read the max field of the 422 rather than hard-coding 25,000.
Use --fail-with-body on every call. With a plain curl -s -o leads.csv, curl exits 0 on a 422 and writes the JSON error into leads.csv, so a spreadsheet or BI sync would ingest the error body as if it were the lead book.
| Query param | Notes |
|---|---|
status | Exact match |
county | Case-insensitive, applied to the full result set |
assignedUser | User ID |
tags, exclude_tags | Same normalized any-of and none-of filters as List Leads, maximum 20 each |
updated_after, created_after | Same strict ISO 8601 timestamp filters as List Leads; invalid values return 400 |
archived | include by default, exclude, or only |
curl -s --fail-with-body "https://<your-domain>/api/v1/leads/export?status=lead" \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-o leads.csv
Response 200, Content-Type: text/csv
Columns: leadId, status, source, displayName, firstName, lastName, phone, email, address, city, state, zip, county, assignedTo, createdAt.
Too many rows 422, Content-Type: application/json
{
"success": false,
"code": "EXPORT_TOO_LARGE",
"message": "Too many rows to export (312,004). This request returns no CSV. ...",
"count": 312004,
"countIsLowerBound": false,
"max": 25000
}
Branch on code, not on the wording of message. count is how many rows matched and max is the ceiling in force. When countIsLowerBound is true, rows were committed between the count and the read, and count is only max plus one: the real total was never measured, so read it as "more than max".
There is no chunked CSV export. To recover from a 422, narrow the match with tags, exclude_tags, status, county, assignedUser, updated_after, or created_after until it is at or under max. If you need the whole book regardless of size, read it as JSON from GET /api/v1/leads (up to 500 rows per page) and build the file on your side. Paging that endpoint is a JSON crawl, not an export.
Export filter example:
curl -s --fail-with-body "https://<your-domain>/api/v1/leads/export?tags=gold&exclude_tags=bronze&updated_after=2026-09-08T00:00:00Z&created_after=2026-01-01T00:00:00Z&archived=exclude" \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" -o leads.csv
Update Lead
PATCH /api/v1/leads/:leadId · Scope: leads:update
Only the fields you send are changed. Omitted fields are left alone.
| Field | Writes to |
|---|---|
status, assignedTo, notes, interestLevel, sellerAskingPrice, monthsDelinquent | Lead |
address, city, state, zip, county | Property |
auctionDate, recordDate, caseNumber, estLoanBalance, estEquity, ltvRatio, noticeUrl, saleStatus, openingBid | Foreclosure record |
auctionDate, openingBid, upsetBid, upsetDeadline, caseNumber, county | Auction tracking |
tags, distressType | Lead tags |
isDeceased, dncSms, dncVoice | Contact suppression flags |
isAbsentee, zillowUrl | Property |
deadReason, deadNotes, doNotMail, doNotMailReason | Lead |
lostDealValue | Attached deal's loss financials when entering dead |
isVacant | Mapped to the vacant lead tag, not a column |
sellerPath, foreclosureStage | See the campaign-control note below |
curl -X PATCH https://<your-domain>/api/v1/leads/LEAD_ID \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "status": "opportunity", "notes": "Owner called back, wants an offer" }'
ltvRatio accepts a number from 0 through 500, including zero. It is stored through the foreclosure writer and returned as foreclosure.ltvRatio by Get Lead. Other types, null, and out-of-range values return 400 before writes.
curl -X PATCH https://<your-domain>/api/v1/leads/LEAD_ID \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" -H "Content-Type: application/json" \
-d '{ "ltvRatio": 61.5 }'
Response 200
{
"success": true,
"leadId": "uuid-...",
"updated": ["status", "notes"],
"enrolledCadenceName": null
}
updated lists the fields whose values this call projected onto the lead's record. Diff it against what you sent. A field you passed that does not come back in updated did not project onto the lead. Evidence may still have been recorded, so an absent field does not mean no database column was written. Check notProjected for a value refused by fact selection instead of assuming a 200 means everything landed.
Extra keys appear only when relevant:
| Key | When | Meaning |
|---|---|---|
enrolledCadenceName | always | The cadence a sellerPath change enrolled the lead into, or null |
sellerPathOutcome | you sent sellerPath and it was applied | What the path change did to the lead's campaigns, described under Set Seller Path |
notProjected | a supplied case number did not project | Field names, currently ["caseNumber"], omitted from updated because the requested value did not become the displayed value |
winningCaseNumber | notProjected is present | The displayed case number, equal to Get Lead's foreclosure.caseNumber and auction.caseNumber, or null when no case number is displayed |
winningCaseKey | notProjected is present | The winning observation's normalized identity, resolved through filing fallback and jurisdiction aliases; a filing-only winner uses filing:<id>. This is an identity key, not the displayed case number |
dead | status changes to dead | { "cancelledEnrollments": 1, "handedOffThreads": 1, "dealClosed": true }, reporting completed side effects. cancelledEnrollments counts the enrollments this call actually cancelled. |
stageError | you sent sellerPath and foreclosureStage, the seller path committed, and the stage change then failed | { "message": "...", "status": 500 }. The seller path and sellerPathOutcome stand; foreclosureStage is absent from updated. Retry the stage on its own |
stageEnrollment | you sent foreclosureStage | The enrollment outcome object described under Set Foreclosure Stage |
applied: false, reason: "lead_not_marketable" | you sent sellerPath or foreclosureStage on a lead that is dead, archived, or merged | Every other field in the request still applied. The path or stage was skipped. |
mapped: { "isVacant": "tag:vacant" } | you sent isVacant | Reminder that it became a tag |
Notes
caseNumbermust be a nonblank string. It is trimmed before recording and comparing the projection. Non-string values other thannull, empty strings, and whitespace-only strings return400before any lead, contact, property, or foreclosure changes.nullis ignored and is not listed inupdated.- An accepted single-lead
caseNumbercorrection pins the selected case across later county and import writes. A later manual card save or accepted single-lead PATCH replaces that choice. Sale, dismissal, release, or removal of all observations for the pinned case releases it. Bulk writes do not create pins and retain earliest-deadline selection when no operator choice is active. - Changing
statusstampsstatusChangedAt, which drives pipeline aging reports. - Changing
statustodeadarchives the lead, cancels every active and paused cadence enrollment, hands the AI texting responder off to humans, and closes the first attached deal as lost with loss financials. deadReasonis optional. On entry todead, a missing, null, empty, or whitespace-only reason defaults toother; otherwise it is trimmed.deadNotesis optional text or null.lostDealValueis an optional number or null, defaulting to the deal's contract price, then offer amount, then zero.- Sending
deadagain on an already-dead lead does not rerun those side effects or return adeadobject. A supplieddeadReasonordeadNotesstill updates the lead. - Leaving
deadclears the dead reason, notes, and reactivation date in the status update, un-archives the lead, and re-enables responder threads that were handed off for being dead. It does not enroll a cadence immediately. - An unknown
status, includingarchived, returns400with{ "success": false, "message": "Invalid status. Allowed: ..." }. The message lists every allowed status. assignedTomust be a user in your organization, otherwise403.- Tags are replaced, not merged. Sending
tagsordistressTyperetracts any tag your integration previously set and is not in the new list. Send the complete tag set every time. To add a tag without touching the others, use Add Tags instead. - A tag that an import or a conversation also holds stays on the lead until someone removes it on the lead page.
sellerPathandforeclosureStagechange what the lead is being sent, not just what it says. Both can cancel the campaign the lead is on and start a different one. If you only want to record the fact, that is still what these do. See Set Seller Path and Set Foreclosure Stage for the full behavior and the dedicated endpoints.- Sending
foreclosureStageon a lead with no foreclosure record returns404, and nothing else in the request is applied because the check runs first. Split the call if you are updating both. "foreclosureStage": nullclears the stage. Clearing enrolls no stage cadence and leaves the campaign the lead is on alone. The dedicated Set Foreclosure Stage endpoint only sets a stage; clear it here.- Setting
doNotMailstampsdoNotMailAtand clearsdoNotMailBy. dncSmsanddncVoiceare contact-wide flags. They are not the per-number opt-out state, and setting them tofalsedoes not release a STOP. See Per-Number DNC.
| Status | Meaning |
|---|---|
400 | Unknown status, or a suppression or condition field failed validation (sellerPath, foreclosureStage, isDeceased, dncSms, dncVoice, isAbsentee, zillowUrl, deadReason, deadNotes, lostDealValue, doNotMail, doNotMailReason, isVacant) |
404 | Lead not found, or it belongs to another organization, or you sent foreclosureStage for a lead with no foreclosure record |
403 | assignedTo is a user outside your organization |
Archive Lead
DELETE /api/v1/leads/:leadId · Scope: leads:update
This archives the lead. It does not delete it. The record, its history, and its contact remain in the database and can be restored in the UI.
{ "success": true, "message": "Lead archived" }
Assign Lead
POST /api/v1/leads/:leadId/assign · Scope: leads:assign
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/assign \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "userId": "USER_UUID" }'
Response 200
{ "success": true, "leadId": "uuid-...", "assignedTo": "uuid-..." }
Returns 400 if userId is missing and 403 if the assignee is not in your organization. The assignment is written to the lead's activity log.
Bulk Update Leads
POST /api/v1/leads/bulk-update · Scope: leads:update
Applies updates to many leads in one request. Each item is processed independently, so a bad row does not abort the rest.
curl -X POST https://<your-domain>/api/v1/leads/bulk-update \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{
"updates": [
{ "leadId": "uuid-a", "status": "dead" },
{ "leadId": "uuid-b", "status": "lead", "assignedTo": "USER_UUID" }
]
}'
Per-item fields: leadId (required), ltvRatio (number 0-500), estEquity, estLoanBalance, status, deadReason, deadNotes, lostDealValue, assignedTo, tags, distressType, auctionDate, recordDate, openingBid, upsetBid, upsetDeadline, caseNumber, county.
For example, {"updates":[{"leadId":"LEAD_UUID","ltvRatio":61.5}]} writes LTV through the same foreclosure writer as PATCH. An invalid LTV is reported in that item's errors entry and the item is not written.
Each item follows the dead-lead rules of Update Lead. Entering dead archives the lead, cancels active and paused cadences, hands the AI texting responder off to humans, and closes the first attached deal as lost with loss financials. The optional deadReason defaults to other when missing or blank, deadNotes accepts text or null, and optional numeric lostDealValue defaults to contract price, offer amount, or zero. Repeating dead only updates supplied metadata. Leaving dead clears dead metadata, un-archives the lead, and re-enables threads handed off for being dead without immediately enrolling a cadence.
Unknown statuses are reported per item in errors with Invalid status. Allowed: ...; that item is not written or counted in updated. Other items continue. The bulk response keeps the counts and errors below and does not add the single-update dead object.
Response 200
{
"success": true,
"updated": 1,
"failed": 1,
"errors": [{ "leadId": "uuid-a", "message": "Lead not found" }]
}
The errors array is capped at the first 50 failures. failed is the true count.
Add Tags
POST /api/v1/leads/:leadId/tags · Scope: leads:update
Adds tags. This is the additive one. Update Lead replaces the whole tag set; this endpoint leaves existing tags alone, which is what you want when your integration owns one label and a human owns the others.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/tags \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "tags": ["Gold", "graded 2026-09"] }'
Accepts either tags (an array) or tag (a single string).
Response 200
{ "success": true, "leadId": "uuid-...", "tags": ["foreclosure", "gold", "graded_2026_09"] }
The returned tags is the lead's complete tag set after the add, not just what you sent. Read it rather than assuming, because tags are rewritten on the way in.
Tag normalization
Every tag is slugified before it is stored. In order: trimmed, lowercased, apostrophes deleted, every run of non-alphanumeric characters replaced with a single underscore, leading and trailing underscores stripped, truncated to 80 characters, and finally mapped through a synonym table that folds known variants onto one canonical tag.
So "Gold", "gold" and " GOLD " are the same tag, and "graded 2026-09" is stored as graded_2026_09. Match on the normalized form when you read tags back, and do not expect the string you sent to survive verbatim.
Notes
- Adding a tag the lead already has is a no-op, not an error. Re-sending the same tags on every sync is safe.
- Maximum 80 characters per tag, and at most 50 tags per request.
| Status | Meaning |
|---|---|
400 | A tag was empty, not a string, or over 80 characters, or the request carried more than 50 tags |
404 | Lead not found, or it belongs to another organization |
Set Seller Path
PATCH /api/v1/leads/:leadId/seller-path · Scope: leads:update
Records what the seller is actually doing, and switches the lead onto the matching contextual campaign. This is not a status field. Setting it can cancel the campaign the lead is on right now and enroll a different one.
curl -X PATCH https://<your-domain>/api/v1/leads/LEAD_ID/seller-path \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "sellerPath": "listed_with_agent" }'
Values
| Value | Meaning |
|---|---|
bankruptcy_considering | Considering bankruptcy |
bankruptcy_filed | Filed. Also stamps bankruptcyFiledAt, which the cadence guard and the AI responder both read |
loan_mod_considering | Considering a loan modification |
loan_mod_active | Modification in progress |
reinstating | Working to reinstate the loan |
reinstated | Reinstated |
listing_considering | Considering listing with an agent |
listed_with_agent | Listed |
other_investor_considering | Talking to another investor |
other_investor_contract | Under contract with another investor |
not_interested_6mo | Not interested, revisit in 6 months |
not_interested_1yr | Not interested, revisit in 12 months |
null | Clears the path. Any active or paused campaign on the lead is cancelled; outcome.stopped says how many |
Response 200
{
"success": true,
"lead": { "...": "the updated lead" },
"enrolledCadenceName": null,
"outcome": {
"enrolled": false,
"reason": "outreach_gate",
"cadenceName": "Rescue",
"refusedBy": "outreach_gate_allow_tags",
"stopped": 0,
"failedStep": null
},
"sellerPathOutcome": { "...": "the same object as outcome" }
}
enrolledCadenceName is the cadence the lead was enrolled into, and null whenever nothing was enrolled. outcome (also returned as sellerPathOutcome, the key the combined lead update uses) says what happened and why:
outcome field | Meaning |
|---|---|
enrolled | true only when a campaign started |
reason | enrolled, cleared, unchanged, no_matching_cadence, cadence_switched_off, cadence_not_usable, outreach_gate, no_deliverable_channel, enrollment_conflict, or error |
cadenceName | The campaign that started, the paused Outreach-gate hold, or the switched-off or unusable campaign; otherwise null |
refusedBy | The underlying code: outreach_gate_allow_tags, outreach_gate_block_tags, no_deliverable_channel, lead, contact, or a cadence problem such as EMPTY_CADENCE or CADENCE_AUDIENCE_MISMATCH; otherwise null |
stopped | How many active or paused enrollments stayed cancelled after this call. If a replacement could not start, the campaign this save cancelled is put back, so this can be 0 even though a cancel ran. null means it could not be determined |
failedStep | Only on error: cancel (cancelling failed), after_cancel (whether a campaign started could not be confirmed), or unknown |
Notes
- Sending the path the lead already has is a no-op. Nothing is enrolled and nothing is cancelled, and
outcome.reasonisunchanged. - An Outreach gate hold (
reason: "outreach_gate") creates the matching seller-path campaign paused withpaused_reason: "outreach_gate". It does not send. Resume it from the Cadence tab, or from Settings → Cadences by ticking resume on the Outreach gate save once the lead carries an allowed tag. Adding the tag by itself does not start sending. An inbound enrollment (auto_inbound/auto_inbound_fallback) cancels that paused hold if it is occupying the lead or contact slot, then enrolls. Auction and other automated sources still refuse with no row. - If the replacement campaign cannot start (no matching campaign, switched off, unusable, no reachable channel, or a conflict), any campaign this save cancelled is put back.
outcome.stoppedis how many stayed cancelled after that restore. Clearing the path (null) still stops the campaign and does not put it back. - A seller path set through the API counts as a human decision, because a path is something a person learns in a conversation. It will therefore cancel a paused campaign as well as an active one. If that is not what you want, do not use this endpoint from an automated grader.
bankruptcy_filedis load-bearing beyond the label. It is the same fact the telephony webhook records, and outreach guards key off the timestamp.- On a lead that is dead, archived, or merged the call returns
200withapplied: false, reason: "lead_not_marketable"and changes nothing.
| Status | Meaning |
|---|---|
400 | sellerPath is not one of the values above or null |
404 | Lead not found, or it belongs to another organization |
Set Foreclosure Stage
PATCH /api/v1/leads/:leadId/foreclosure-stage · Scope: leads:update
Moves the lead's foreclosure record to a new stage. A matching stage cadence preempts the lead's campaign: it cancels what is running and enrolls the stage cadence, so the message the homeowner gets next matches where the case actually is.
curl -X PATCH https://<your-domain>/api/v1/leads/LEAD_ID/foreclosure-stage \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "stage": "sale_postponed" }'
Values: pre_foreclosure, lis_pendens, hearing_scheduled, continued_1, continued_2, continued_3plus, judgment_entered, auction_set, auction_complete, redemption_period, sale_scheduled, sale_completed, sale_postponed, sale_cancelled, dismissed
Response 200
{
"success": true,
"foreclosureData": { "...": "the updated foreclosure record" },
"enrolled": true,
"enrollment": {
"enrolled": true,
"cadenceName": "Sale Postponed Follow-Up",
"reason": "enrolled",
"preempted": 1
}
}
enrollment.reason
| Reason | Meaning |
|---|---|
enrolled | The stage cadence took over. preempted is how many enrollments it cancelled to do it. |
no_matching_cadence | No cadence is configured for this stage. The stage was still written. |
already_enrolled | The lead is already on that cadence. |
held | A deliberate hold blocked it. heldBy carries the paused_reason. Read this one. |
refused | The enrollment was rejected downstream, for example no deliverable channel. |
error | Bookkeeping failed. The stage was written; the campaign may not have changed. |
Notes
- A stage change pushed through the API counts as a machine actor, and a machine may not cancel a deliberate hold. If the campaign is paused because the homeowner replied, because a compliance rescreen is running, or because authorization was revoked, the new cadence is refused and you get
reason: "held". That is intentional. A docket update happens with nobody in the room, and it must not restart outreach a person stopped. - A machine actor can take over a campaign parked on a
processing_error_*reason, because that is a machine's own park, not a decision. - Re-sending the stage the lead is already on still writes the stage and still logs the change to the timeline, but it enrolls nothing: the cadence check runs only when the stage actually differs. It is safe to replay, it is just not silent.
- On a lead that is dead, archived, or merged the call returns
200withapplied: false, reason: "lead_not_marketable". - When
reasonisheld, the campaign still running is now the wrong one for the case. Nothing resumes it automatically, so decide in your own system whether to follow up.
| Status | Meaning |
|---|---|
400 | stage is not one of the values above |
404 | Lead not found, it belongs to another organization, or the lead has no foreclosure record |
Enroll in a Cadence
POST /api/v1/leads/:leadId/cadence-enroll · Scope: leads:update
Puts a lead on a specific cadence. Send exactly one of cadenceId or cadenceName. Optional reference is your 1 to 100 character label for a newly created enrollment.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/cadence-enroll \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "cadenceName": "Gold Seller Outreach", "reference": "your-system-id" }'
Response 200
{ "success": true, "enrolled": true, "enrollmentId": "uuid-...", "conflictReason": null, "reference": "your-system-id" }
When enrolled is false, conflictReason says why:
| Reason | Meaning |
|---|---|
lead | The lead is already on an active or paused cadence. Cancel it first to enroll a different cadence. |
contact | Another lead for the same contact is already enrolled. Only one campaign per person. |
no_deliverable_channel | Every communication step targets a channel this contact cannot receive: per-number DNC or opt-out, a compliance hold, a bounced or missing email. Enrolling would create a visibly active cadence that can never send anything. |
dead_lead | The lead's status is dead. |
Notes
cadenceNamematches case-insensitively. Your organization's own cadence wins over a shared platform cadence of the same name. If two of your cadences share a name, you get409and must usecadenceId.enrolled: falseis a200, not an error. Check the field.- This endpoint never preempts. Unlike a stage or seller-path change, it will not cancel a running campaign to make room.
- Every 200 response includes
reference. It is the stored value only for a newly created enrollment and is otherwise null.
| Status | Meaning |
|---|---|
400 | Neither or both of cadenceId and cadenceName were sent |
400 | reference is not 1 to 100 characters |
404 | Lead not found, it belongs to another organization, or no cadence matched |
409 | The cadence name is ambiguous within your organization |
503 | A reference was sent but the server has not yet created its reference table |
Outreach approval gate
GET /api/v1/settings/outreach-gate and PUT /api/v1/settings/outreach-gate
The GET requires leads:read or leads:update; the PUT requires leads:update. Settings apply only to the authenticated key's organization.
The gate controls outreach the platform starts automatically, including imports, the county feed, sweeps, drips, status changes, and cadence chains. It never blocks operator-started Start Outreach, explicit API enrollment, the dialer, AI caller campaigns, inbound AI replies, or the automatic follow-up to a lead who contacted you first (inbound sources are exempt).
| Mode | Behavior |
|---|---|
off | Default. Automated outreach is allowed. |
allow_tags | A lead must carry at least one selected tag. An empty list holds all automated outreach. |
block_tags | A lead must carry none of the selected tags. An empty list blocks nothing. |
curl -X PUT https://<your-domain>/api/v1/settings/outreach-gate \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "mode": "allow_tags", "tags": ["gold", "silver"], "pauseNonMatchingNow": true, "resumeGatePausedNow": false }'
PUT requires mode and tags. Tags are normalized with the shared tag rules and deduplicated;
send at most 50 strings, each 1-64 characters before and after normalization. Invalid input
returns 400. pauseNonMatchingNow is an optional boolean, default false. When true, active
automated enrollments on leads failing the rule are paused with paused_reason: "outreach_gate".
Manual and explicit API enrollments stay running. Saving a more permissive rule does not
automatically resume paused enrollments: pass resumeGatePausedNow: true to resume the enrollments
this gate paused whose lead now passes the rule (operator pauses are never touched). repended
counts drip candidates the gate had refused that were put back in line by this save; the drip
processor also re-queues a held candidate on its own once the lead's tags satisfy the gate.
PUT response (200):
{ "success": true, "mode": "allow_tags", "tags": ["gold", "silver"], "updatedAt": "2026-09-08T12:00:00.000Z", "paused": 12, "resumed": 0, "repended": 3 }
GET returns the settings plus gatePaused, the number of enrollments currently paused by this gate.
An organization with no saved setting gets
{ "success": true, "mode": "off", "tags": [], "updatedAt": null, "gatePaused": 0 }.
Enrollment tooling may report conflictReason: "outreach_gate_allow_tags" or
"outreach_gate_block_tags" for refused automated claims. These values describe why no
cadence_enrollments row was created. Seller-path saves that pause on the gate instead
report the same codes on outcome.refusedBy (the paused row exists). Explicit
POST /api/v1/leads/:leadId/cadence-enroll uses source api_v1, bypasses this gate, and
never returns these two reasons.
Pause Cadences
POST /api/v1/leads/:leadId/cadence-pause · Scope: leads:update
Pauses every active enrollment on the lead. Use this as a stop button when your own system learns something that should halt outreach. To replace a cadence, use Cancel Cadences first; a paused enrollment still counts as enrolled.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/cadence-pause \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "reason": "downgraded to bronze" }'
reason is optional and defaults to api_v1. It is stored as the enrollment's paused_reason and is what a later stage change reports back as heldBy, so a specific reason is worth sending.
Response 200
{ "success": true, "paused": 2 }
paused: 0 means there was nothing active to pause. That is a success, not an error.
Notes
- A pause is a deliberate hold. A later machine-actor stage change will not cancel it. That is the point: this is how you stop outreach and have it stay stopped.
- Pausing is not opting out. It stops the campaign, not the number. To suppress a number, use Per-Number DNC.
| Status | Meaning |
|---|---|
404 | Lead not found, or it belongs to another organization |
Cancel Cadences
POST /api/v1/leads/:leadId/cadence-cancel · Scope: leads:update
Cancels every active and paused enrollment on the lead. reason is optional, trimmed, at most 200 characters, and defaults to api_v1. includePaused is an optional boolean that defaults to true; set it to false to leave paused enrollments alone.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/cadence-cancel \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "reason": "replacing campaign", "includePaused": true }'
Response 200
{ "success": true, "cancelled": 2 }
cancelled counts the enrollments this call actually cancelled. An enrollment that finished, or was cancelled by something else, while the call ran is neither changed nor counted. Zero means nothing was cancelled. An invalid body returns 400; an inaccessible or missing lead returns 404. Cancelled enrollments cannot be resumed. Use Enroll in a Cadence for a new enrollment.
Resume Cadences
POST /api/v1/leads/:leadId/cadence-resume · Scope: leads:update
Resumes paused enrollments belonging to the lead in your organization. No body fields are required.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/cadence-resume \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{}'
Response 200
{ "success": true, "resumed": 1, "skipped": [] }
Resume makes the enrollment active, clears its pause and hold state, and schedules its next step for the current database time. Normal send gates still apply. A processing-error hold or unresolved provider attempt must be reconciled by a platform administrator first; refused enrollments remain paused and appear in skipped:
{
"success": true,
"resumed": 0,
"skipped": [{
"enrollmentId": "uuid-...",
"reason": "This cadence has an unresolved provider attempt and must be reconciled before it can resume"
}]
}
A pending stop request can keep an enrollment paused when its lease is released. It is reported in skipped with the stored pause reason and is not counted in resumed.
A lead with status dead or closed, or one that is archived or merged, returns 200 without resuming anything:
{ "success": true, "resumed": 0, "conflictReason": "dead_lead" }
An inaccessible or missing lead returns 404.
Bulk Cadence Operations
POST /api/v1/leads/bulk-cadence, scope leads:update.
The body contains action (pause, cancel, or resume), leadIds (1-500 UUIDs), optional reason (trimmed, maximum 200 characters, default api_v1), and optional includePaused (boolean, default true, used by cancel). Duplicate IDs are processed once. Invalid bodies return 400. Leads are processed sequentially, with a 25-second processing budget checked between leads and, for resume, between enrollments; a cancel of one lead may run past the budget, and a pause applies its whole batch in one statement after the budget has been checked. A call already in progress may finish after that budget; remaining IDs are reported in errors for retry.
curl -X POST https://<your-domain>/api/v1/leads/bulk-cadence \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" -H "Content-Type: application/json" \
-d '{"action":"pause","leadIds":["11111111-1111-4111-8111-111111111111","22222222-2222-4222-8222-222222222222"],"reason":"Review underwriting"}'
Pause affects active enrollments, and takes the same path as the Stop button in the CRM: an idle campaign stops at once, and one that is mid-step is stopped at its next safe point and reported in pausingAfterCurrentStep. Cancel affects active and paused enrollments unless includePaused is false. Resume uses the same guarded resume helper as the per-lead route, and refuses dead, closed, archived, or merged leads with conflictReason: "dead_lead" on that lead's error. Enrollments with unresolved provider attempts or processing errors remain paused and are reported in errors.
Choosing which campaigns to act on. By default a pause or resume takes every matching campaign on each lead you list. Three optional fields narrow it, and they apply to pause and resume only. Sending any of them with action: "cancel" is refused with 400 rather than ignored, because cancel takes a different path that cannot filter, and silently cancelling the campaigns you asked us to spare would be worse than an error.
automatedOnly: trueacts only on campaigns the platform started automatically, and is what you want if you are silencing router drips. It uses the same definition as the Outreach gate, so it cannot drift from the rest of the product.enrollmentSource: ["auto_drip"]acts only on campaigns whose recorded source is exactly one of these strings.excludeEnrollmentSource: ["manual"]never acts on campaigns whose recorded source is exactly one of these strings.
Prefer automatedOnly to naming sources by hand. A campaign started by a person through this API records api_v1, not manual, so excludeEnrollmentSource: ["manual"] would still pause your own team's work. The two explicit lists match exact strings and nothing else, and they treat a campaign with no recorded source differently from each other. enrollmentSource never selects one, because a missing source is not one of the strings you named. excludeEnrollmentSource does act on one, for the same reason: a missing source is not on your exclude list either, so the campaign is not excluded. Only automatedOnly leaves an unlabelled campaign alone, because the product treats one as operator work.
A lead holds at most one active or paused campaign at a time, so these filters decide which leads are affected rather than splitting a single lead. Note also that pausing keeps that slot occupied: if your next step is to start a new campaign on those leads, pause alone will not free them.
This endpoint rejects fields it does not recognise, with a 400 naming the field. That is deliberate and it is the only endpoint here that does it. Every other body would simply ignore a stray key, but a misspelled filter on this one is not a harmless typo: excludeEnrollmentSources, with the s, would have parsed as a request carrying no filter at all and stopped every campaign on every lead in the list. The filters exist to spare work, so a filter we did not understand has to fail rather than be dropped. Send exactly the fields listed above.
The filter is applied at the moment the campaigns are stopped, not when the request arrives, so a campaign whose source changes in between is judged by what it is when we write to it. Resume works the same way, and a campaign that no longer matches is reported in errors rather than resumed.
curl -X POST https://<your-domain>/api/v1/leads/bulk-cadence -H "Authorization: Bearer pfp_YOUR_KEY_HERE" -H "Content-Type: application/json" -d '{"action":"pause","leadIds":["11111111-1111-4111-8111-111111111111"],"reason":"Silence the router","automatedOnly":true}'
Additional request examples:
{"action":"cancel","leadIds":["11111111-1111-4111-8111-111111111111"],"includePaused":true}
{"action":"resume","leadIds":["11111111-1111-4111-8111-111111111111"],"reason":"Review complete"}
Response example:
{
"success": true,
"action": "resume",
"leads": 2,
"enrollments": 2,
"pausingAfterCurrentStep": 0,
"stopRequestsCancelled": 0,
"errors": [
{"leadId":"foreign-lead-uuid","message":"Access denied"},
{"leadId":"dead-lead-uuid","message":"dead_lead","conflictReason":"dead_lead"}
]
}
leads counts eligible leads processed, including those with no matching enrollments. enrollments counts affected enrollments; for cancel, the enrollments this call actually cancelled, by the same rule as cadence-cancel. errors reports each foreign, missing, refused, failed, or unfinished lead; inspect it even when success is true. A partially processed lead can count in leads and also have an error.
stopRequestsCancelled appears on every response and is only ever above zero for resume. A stop that was queued against a mid-step campaign and has not landed yet is called off before anything else happens, so a pause followed by a resume leaves nothing behind. Without that, a campaign you had just resumed would stop itself a few minutes later, and nothing you could call would have prevented it. The same filter applies, so a resume that names only automated campaigns calls off only their queued stops.
pausingAfterCurrentStep appears on every response and is only ever above zero for pause. It counts campaigns our dispatcher had already claimed when you called. That means either a message is in flight with the provider, or the step has been picked up and is about to be generated and sent. Those are not stopped on the spot, because stopping one there can strand a message that is already going out and leave you with a send we never recorded against the lead. The stop is recorded on the campaign and lands at its next step boundary instead, usually within minutes, and it needs no second call from you. Be clear about what that means in practice: the step already under way can still finish, so one more message may go out on those campaigns after your pause has returned. Those campaigns are still active if you read them back immediately, so treat the two counts together as the campaigns this call acted on, and enrollments alone as the ones already stopped. Neither count is meant to match the number of leads you sent. A lead may have had no campaign running, and when you send a filter, leaving campaigns alone is the point of it.
Custom Fields
GET /api/v1/custom-fields, scope leads:read, lists the active custom field definitions for the API key's organization:
{
"success": true,
"customFields": [
{ "key": "custom_loan_balance", "label": "Loan Balance", "type": "currency", "section": "lead" }
]
}
PATCH /api/v1/leads/:leadId/custom-fields, scope leads:update.
Send { "customFields": { ... } }. Keys must match ^custom_[a-z0-9_]{1,60}$. Values are strings of at most 1000 characters, finite numbers, or null. Fields merge with existing answers; null deletes a key. A key that has a definition is coerced and checked against that definition, including while the field is archived. A wrong type returns 400 with errors and changes nothing. Keys the account has never defined still merge as before and are capped at 100 undefined keys per lead. Concurrent API merges preserve both callers' distinct keys.
curl -X PATCH https://<your-domain>/api/v1/leads/LEAD_ID/custom-fields \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" -H "Content-Type: application/json" \
-d '{"customFields":{"custom_ltv":61.5,"custom_key_signals":"equity"}}'
Response:
{"success":true,"customFields":{"custom_ltv":61.5,"custom_key_signals":"equity"}}
Then send {"customFields":{"custom_ltv":null,"custom_final_judgment":200000}} to delete LTV and add the judgment, retaining custom_key_signals. Get Lead returns exactly that merged object in its top-level customFields. List Leads adds it to each row only with ?include=custom_fields. The default list payload has no custom-fields object.
Skip Trace a Lead
POST /api/v1/leads/:leadId/skip-trace · Scope: leads:update
Runs a skip trace against the lead's property and contact. This spends your account's skip trace allowance.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/skip-trace \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "traceMode": "seller", "autoEnroll": false }'
| Field | Default | Notes |
|---|---|---|
traceMode | "seller" | "seller" traces the owner (1 credit on a hit). "family" also buys the named relatives Tracerfy holds, usually around five, and keeps every one it returns: 7 credits when the family lookup returns contact details or relatives, 1 if only the owner is found another way, otherwise 0 (a lookup that finds nothing is not charged). On a Foresight Data lead, 6 when it returns something, otherwise 0. |
autoEnroll | false | When true, a lead that gains a usable phone or email is enrolled into a cadence and outreach starts on its own. Must be sent as the literal boolean true. |
Response 200
{
"success": true,
"result": {
"phones": [{ "phone": "7045550111", "relationship": "self" }],
"emails": [],
"relatives": [{ "name": "Jane Doe", "relationship": "relative", "phone": "7045550222" }]
},
"log": { "creditsUsed": 7, "status": "success", "...": "the rest of the trace log entry" },
"creditsRemaining": 412,
"autoEnroll": false,
"enrolled": false
}
Notes
- This endpoint does not honor
Idempotency-Key. A retry runs a second trace and is billed again. Do not put it behind an automatic retry, and do not let a job runner replay it. autoEnrolldefaults tofalsehere, which is the opposite of the in-app button. Automation should opt in deliberately.- A
402means the account is out of skip trace credit or has hit a plan limit. The response carriescodeandcheckdescribing which. - A rate-limited vendor response sets the
Retry-Afterheader. Respect it. log.creditsUsedis what this trace cost: for"family"7, 1 or 0 as above (6 or 0 on a Foresight Data lead); for"seller"1 or 0.result.relativeslists each relative's name, relationship (always"relative"), and phone or email when known.- A
"family"trace that cannot reach the relatives product fails with nothing charged rather than returning the owner alone.
| Status | Meaning |
|---|---|
400 | Skip tracing is not enabled for the account, credits are exhausted, or the lead has no address and no name to trace on; also "family" requested on an account where family tracing is not available, or on a lead with no contact. Nothing is charged. |
409 | The lead's contact changed while the trace was running (code lead_contact_changed). Nothing is saved or charged; run the trace again. |
402 | Plan or usage limit reached. See code and check. |
404 | Lead not found, or it belongs to another organization |
User Endpoints
List Users
GET /api/v1/users · Scope: leads:read
Lists active and inactive users in the key's organization. Foresight's own support sign-in is not a team member and is never listed. Each object has exactly id, firstName, lastName, name, email, role, and isActive. name joins first and last name and is null when neither is stored. Results sort by name case-insensitively, unnamed users last, then by ID.
{
"success": true,
"users": [
{
"id": "uuid-...",
"firstName": "Alex",
"lastName": "Rivera",
"name": "Alex Rivera",
"email": "alex@example.com",
"role": "admin",
"isActive": true
}
]
}
Get User
GET /api/v1/users/:userId · Scope: leads:read
Returns { "success": true, "user": { ... } } with the same seven fields. An ID outside the key's organization returns 404.
Pulse Score
Get Lead always includes pulse, while List Leads includes it when include=pulse is requested. The score is calculated on read from organization-scoped contact, property, foreclosure, intake pillar, and weight records. It is not stored. score is the weighted overall percentage, grade is the displayed letter grade, and each of leadIntake, property, occupancy, condition, motivation, and financials contains score, weight, filledFields, totalFields, and missingCritical. Top-level criticalMissing summarizes the most important gaps and computedAt is the response-time calculation timestamp.
The pulse block on Get Lead and on each List Leads row with include=pulse:
{
"score": 53,
"grade": "C+",
"pillars": {
"leadIntake": { "score": 90, "weight": 15, "filledFields": 7, "totalFields": 7, "missingCritical": [] },
"property": { "score": 70, "weight": 10, "filledFields": 5, "totalFields": 6, "missingCritical": [] },
"occupancy": { "score": 55, "weight": 10, "filledFields": 1, "totalFields": 3, "missingCritical": [] },
"condition": { "score": 32, "weight": 15, "filledFields": 2, "totalFields": 8, "missingCritical": [] },
"motivation": { "score": 41, "weight": 25, "filledFields": 2, "totalFields": 5, "missingCritical": ["Life Event"] },
"financials": { "score": 47, "weight": 25, "filledFields": 3, "totalFields": 9, "missingCritical": [] }
},
"criticalMissing": ["Life Event (Motivation)"],
"computedAt": "2026-11-06T13:00:00.000Z"
}
grade comes from score: 90 and up is A+, 80 is A, 70 is B+, 60 is B, 50 is C+, 40 is C, 35 is D, and anything lower is F.
Get Lead also returns pillars, a flat object of the stored intake facts. Each field is null when unset: reasonForSelling, askingPrice, cmaAvm, timeFrame, mortgageBalance, occupancyStatus, tenantLeaseTerm, tenantRentAmount, tenantCooperating, vacantDuration, vacantSecured, vacantUtilitiesOn, personalProperty, petsAnimals, conditionOverall, roofCondition, hvacCondition, foundationIssues, waterDamageMold, electricalPlumbing, rehabLevel, estimatedRepairCost, motivationScore, lifeEvent, monthsBehind, hasPlanB, familyInvolved, sellerGoal, sellerAwareOfSaleDate, lenderLettersReceived, monthlyPayment, interestRate, amountInArrears, lastMortgagePaymentDate, hoaBalanceOwed, taxLiensOwed, otherLiens, otherLiensAmount, isUnderwater, sellerWalkAwayPrice, updatedAt.
Message Endpoints
List Messages
GET /api/v1/messages requires messages:read (or full access).
Query parameters: limit defaults to 50 and clamps to 1 through 200; order is desc (default) or asc; since is inclusive and until exclusive, both ISO 8601 timestamps with an offset; direction is inbound or outbound; lead_id is a UUID; needs_reply accepts only true; cursor is the opaque, order-bound next-page cursor.
Returns { success: true, messages: [...], nextCursor: string | null, hasMore: boolean }. Each message includes id, leadId, direction, full body, fromNumber, toNumber, createdAt, sentAt, delivery status, errorCode, channel, mediaUrls, and sentBy. Sender precedence is inbound { type: "contact" }, outbound cadence { type: "cadence", cadenceEnrollmentId }, AI { type: "ai" }, teammate { type: "user", userId, name }, then { type: "system" }. A teammate outside the account has null userId and name.
needs_reply=true uses the same inbox builder and per-org cache as the in-app Needs Reply inbox. Membership follows the exact stored buckets folded into each waiting conversation, including relinked and collapsed threads. Another lead sharing a number is a separate bucket. Results may be stale for the inbox cache window (normally five seconds). The API returns messages from those buckets, never inbox display enrichment. Demo, AI shadow, and SMS retention rows are excluded. Lead-linked messages belong to the lead's organization; leadless messages belong to their stored organization.
For keeping in sync, use since with an overlap and deduplicate by message id, following nextCursor until hasMore is false. Ordering uses created time (null uses the Unix epoch) then id; timestamps preserve microseconds. Cursors are unsigned page positions and cannot grant access outside the key's organization.
List Lead Messages
GET /api/v1/leads/:leadId/messages requires messages:read. Accepts the same filters except lead_id. Resolves merged leads within the account in a read-only repeatable-read transaction, returns leadId for the survivor alongside the page, and returns 404 if the requested lead is outside the account or missing.
List Lead Emails
GET /api/v1/leads/:leadId/emails requires messages:read (or full access). Read-only keys can call it. Email bodies are readable with messages:read; there is no separate email scope.
Query parameters: limit defaults to 10 and clamps to 1 through 20 (lower than /messages because each email carries a full body); order, since, until, direction and cursor work exactly as on List Messages. lead_id and needs_reply are not supported here and return 400. Merged leads resolve within the account the same way as List Lead Messages; a lead outside the account or missing returns 404.
Returns { success: true, leadId, emails: [...], nextCursor: string | null, hasMore: boolean }. Each email includes:
id,leadId,dealId,direction(inboundoroutbound),status(delivery status),createdAt,sentAt,openedAt,clickedAt,bouncedAt.subjectandsubjectTruncated;body,bodyTruncatedandbodyLength(the stored length in characters).from,to,cc: for inbound email, parsed from theFrom:,To:andCc:header lines Foresight stores at the top of the message, and removed frombody.nullwhen not stored, and alwaysnullfor outbound email (Foresight does not store the outbound sender, and stores To and Cc together).recipients: inbound,tothenccwith duplicates removed; outbound, the recipients Foresight recorded when it sent (empty for cadence and bulk sends, which do not record them).recipientsTruncatedis true when any list was cut.thread:{ key, subject }. Foresight does not store a reply chain per email, so the thread is derived from the subject:thread.subjectis the subject with leadingRe:,Fwd:,Fw:andAw:prefixes removed and whitespace collapsed, andthread.keyis that text lowercased. Emails with the same key are replies on the same subject. An empty subject gives key""and subjectnull. Two different subjects that share their first 1,000 normalized characters share a key.sentBy, with the same precedence as messages: inbound{ type: "contact" }, cadence{ type: "cadence", cadenceEnrollmentId }, AI{ type: "ai" }, teammate{ type: "user", userId, name }, then{ type: "system" }.
Size limits, so a page always has a bound:
bodyis at most 50,000 characters,subject,thread.subjectandthread.keyat most 1,000 each, and each address at most 254. A cut sets the matching...Truncatedflag; a value within its limit is never cut.toandccat most 25 addresses each,recipientsat most 25 in total.- Characters are counted as Unicode code points.
Bodies are returned as stored. Emails sent from the lead page composer and bulk email may be HTML. Inbound email is plain text with the quoted earlier reply removed on a best-effort basis. Imported (migrated) emails keep the subject inside the body.
Routing addresses are redacted. Foresight's own reply and routing addresses (lead reply addresses, deal and TC mailbox aliases, agent outreach aliases and digest reply addresses) contain private tokens. Wherever one appears, in a subject, a body or an address, its token is replaced by [redacted] (or by one * per character for a token shorter than 10 characters), including spellings an email parser would still read as that address (quoted, escaped, or split by comments or quoted text). When a token is cut or cannot be read cleanly, the rest of that value from the token onward is replaced. Redaction never makes a value longer and changes only the response, never stored data. It can occasionally hide ordinary text that looks like one of these tokens.
POST /api/v1/leads/:leadId/emails is a different call: it adds an email address to the lead's contact (contacts:update).
Call Endpoints
Call records from the human dialer, AI caller, and AI receptionist share one response shape. Each record is one call leg. For example, an inbound call that rings a rep and is then answered by the AI receptionist produces two records.
List AI Conversations
GET /api/v1/ai-conversations · Scope: leads:read
Lists AI texting conversations in the API key's organization, one record per thread. Message bodies are available through the Messages endpoints. Conversations page by their immutable start time, not last activity. Use updatedAt for change detection.
| Query param | Default | Notes |
|---|---|---|
limit | 50 | Integer string, clamped to 1 through 200 |
order | desc | asc or desc |
since | none | Inclusive start time, ISO 8601 with offset |
until | none | Exclusive start time, ISO 8601 with offset |
cursor | none | Opaque nextCursor from the previous page, with the same order |
Repeated query values and invalid timestamps or cursors return 400. Sort order is start time, rank (0), then ID; a missing start time sorts as 1970-01-01. The response is { success: true, conversations: [...], nextCursor: string | null, hasMore: boolean }.
Each conversation returns id, leadId, phone, status, outcome, goal, lastIntent, turnCount, aiReplyCount, startedAt, updatedAt, lastInboundAt, lastAiTurnAt, escalatedAt, escalationReason, handoffReason, handoffSentAt, agentTakeoverAt, optedOutAt, bookedAppointmentId, and lead. leadId and lead are null unless the linked lead belongs to the key's organization. When that lead was merged into another lead, leadId and lead are the surviving lead, the same one Get Lead returns for the old ID. lead has the same { id, displayName, address, city, state, zip } shape as List Calls. Times are ISO UTC strings with microseconds, or null. escalationReason is a safe, plain-language description. Unsent staged replies and internal model/provider text are never returned.
lastAiTurnAt is the last time the AI processed a turn on this thread, including turns where it chose not to reply or ran in shadow mode; it is not proof a text was sent.
outcome uses the first matching rule:
opted_out:optedOutAtis set or status isopted_out.booked:bookedAppointmentIdis set or status isbooked.escalated: status isescalated.handed_off: status ishanded_offorpaused, oragentTakeoverAtis set.closed: status isclosed(the AI ended without a booking) orwrong_number(the contact said it is the wrong number).in_progress: everything else, includingactive,awaiting_confirmation, and unknown statuses. The original status is always returned.
List Lead AI Conversations
GET /api/v1/leads/:leadId/ai-conversations · Scope: leads:read
The same query parameters, fields, outcome rules and start-time pagination as List AI Conversations. Resolves merged lead IDs to the surviving lead in the key's organization. Conversations still recorded on a lead that was merged into this one (at any depth, same organization) are included, because lead merges do not move conversations. Returns { success: true, leadId, conversations, nextCursor, hasMore }, where leadId is canonical. Returns 404 for a missing or foreign lead. Legacy threads with null organization are included only when they belong to this organization's lead.
Lead Timeline
GET /api/v1/leads/:leadId/timeline · Scope: leads:read
Returns { success: true, leadId, events, nextCursor, hasMore } for the canonical surviving lead, or 404 for a missing or foreign lead. Accepts the same limit, order, since, until, and cursor parameters as List AI Conversations. Newest first by default, ordered by event time, rank, then ID; since is inclusive and until exclusive. Each event is { id, type, occurredAt, actor, details }. Times are ISO UTC strings with microseconds, or null.
| Type | Rank | Event time | Details |
|---|---|---|---|
note | 0 | Original sent time, falling back to creation time, then 1970-01-01 | body, subtype |
stage_change | 1 | Recorded transition time | fromStage, toStage, daysInPreviousStage |
task | 2 | Creation time, falling back to 1970-01-01 | title, description, taskType, status, priority, dueAt, completedAt, assignedToUserId |
There is one event per task at creation, with its current details. Manual Stage Timeline corrections are not applied to recorded stage changes. Actor precedence is { type: "ai" } for an AI note, even if a user is also stored; otherwise { type: "user", userId, name } when an actor was stored, or { type: "system" }. A foreign user's ID and name are null. assignedToUserId is null unless the assignee belongs to the organization. Every event row must belong to the key's organization or be a legacy null-organization row on this organization's lead.
List Calls
GET /api/v1/calls · Scope: calls:read
Lists call records owned by the API key's organization. A legacy call with no organization attribution is excluded here. It can appear only in List Lead Calls when its lead currently belongs to the organization.
| Parameter | Default | Description |
|---|---|---|
limit | 50 | Page size, clamped to 1 through 200 |
order | desc | asc or desc by the stable recorded time, source rank, and ID |
since | none | Inclusive ISO 8601 instant with an explicit offset |
until | none | Exclusive ISO 8601 instant with an explicit offset |
direction | none | inbound or outbound |
source | none | dialer, ai_caller, or ai_receptionist |
phone | none | A US or Canadian number. Matches either party in common 10 digit, 1 plus 10 digit, or +1 format |
cursor | none | Opaque cursor returned by the preceding page |
Resend the same filters with every cursor. Never inspect, modify, or build a cursor. Follow nextCursor until it is null.
curl -s "https://<your-domain>/api/v1/calls?order=asc&since=2026-09-25T00:00:00Z&limit=100" \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE"
The response is { "success": true, "calls": [...], "nextCursor": string | null, "hasMore": boolean }. Every call has these fields:
| Field | Meaning and null behavior |
|---|---|
id | Call record ID |
source | dialer, ai_caller, or ai_receptionist |
direction | inbound or outbound |
leadId | Lead ID only when that lead currently belongs to this organization, otherwise null |
fromNumber, toNumber | The two call party numbers |
recordedAt | Stable listing time. Dialer start time or AI record creation time. Null only when the dialer row's start time or the AI row's creation time is null |
startedAt, answeredAt, endedAt | Actual lifecycle times, each null when not recorded yet or unavailable |
durationSeconds | Dialer duration or AI duration in seconds, null when unavailable |
status, outcome | Source status and outcome, each null when unavailable |
isVoicemail | Dialer voicemail flag, or true when an AI call outcome is voicemail |
notes | Rep notes for dialer calls, otherwise null |
summary | AI call summary for AI calls, otherwise null. Internal provider diagnostics are returned as null |
motivationLevel | Dialer AI motivation score or AI call motivation level, null when unavailable |
appointment | { "at", "type" } for an AI call with an appointment time, otherwise null. type can be null |
handledBy | Tenant rep { "type": "user", "userId", "name" }, AI { "type": "ai", "name" }, or null. A dialer call linked to a rep outside this organization returns null for both user fields |
hasRecording, hasTranscript | Booleans indicating availability. Recording audio is not returned; a transcript is returned only by Get Call with include=transcript |
lead | { id, displayName, address, city, state, zip } for an organization lead, with null address fields if its property is unavailable, otherwise null |
Every time is an ISO 8601 UTC string with microseconds, for example 2026-09-25T12:00:00.000500Z. This includes recordedAt, startedAt, answeredAt, endedAt, and appointment.at.
List Lead Calls
GET /api/v1/leads/:leadId/calls · Scope: calls:read
Lists calls for one lead. If the requested lead was merged, the endpoint follows the full merge chain and returns the surviving lead ID as top-level leadId. A missing lead or a lead owned by another organization returns 404.
It accepts limit, order, since, until, direction, source, and cursor exactly as List Calls. It does not accept phone. Its response adds the surviving leadId to the List Calls response. Legacy call rows with a null organization are included only while that surviving lead belongs to the API key's organization.
Get Call
GET /api/v1/calls/:callId · Scope: calls:read
One call, in the same shape as an item of List Calls, returned as { "success": true, "call": { ... } }. It finds calls owned by the API key's organization and legacy null-organization calls whose lead currently belongs to the organization, matching List Lead Calls; test AI calls remain excluded. Anything else, including a call of another organization, returns 404. An optional source (dialer, ai_caller or ai_receptionist) narrows the lookup. Use include=transcript to add transcript, as text or null, for this one call. Include parsing is lenient, so blanks and unknown tokens are ignored and repeated or comma-separated values work. List endpoints never return transcripts. Use the source with an outgoing webhook event's callId and source.
Keeping in sync
since and until select by when Foresight recorded the call, which never changes. For dialer calls this is the call start time. For AI calls it is when the call was created, including time spent queued. Other fields can change later. Outcome and AI summary usually settle within minutes of the call, while a rep can edit notes at any time with no time limit.
For regular polling, use order=asc, overlap the previous poll's since by a few hours, and treat each id as an upsert. This catches new records and changes made within that overlap. A daily re-read of the last 30 days catches changes made within 30 days of the call. Changes to older calls, and records inserted with a recorded time older than the re-read window, are seen only by re-reading a wider window. The latter is rare and can happen when calls are recovered from Twilio after an outage.
Paging is a live read, not a snapshot. A record inserted during a walk with a recorded time behind the current cursor is not returned by that walk. The next poll returns it when the poll window covers its recorded time.
What is kept and for how long
An admin permanently deleting a lead in the app removes its call records and transcripts. The public API delete only archives a lead, so it removes no call record or transcript. Deleting an AI agent deletes that agent's AI calls and campaigns, and deleting an AI campaign deletes that campaign's AI calls. Recording audio is held by the phone provider, so Foresight does not promise how long audio stays playable.
Contact Endpoints
Add Phone Numbers
POST /api/v1/leads/:leadId/phones · Scope: contacts:update
Appends to the contact's additional phone list. Does not change the primary phone. A number already on the contact is not stored again.
Each entry is either a string, which is the owner's own number, or an object { "phone", "relationship", "name", "type" }. Give a relative's number a relationship (spouse, child, parent, sibling, relative, or another word, which is stored as unknown) and the person's name: it is stored as that person's number, not the owner's, and the person is added to the lead's Family / Related Contacts list. A relative's number is never promoted to the primary phone, which is the number automated texts use.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/phones \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "phones": ["6145551234", { "phone": "6145555678", "relationship": "spouse", "name": "Jane Doe" }] }'
{ "success": true, "contactId": "uuid-...", "added": 2, "alreadyOnContact": 0, "totalPhones": 3 }
added is how many numbers were stored, alreadyOnContact how many were skipped because the contact already had them, and totalPhones counts the additional phones plus the primary, if set. An entry that is neither a string nor an object with a phone returns 400 with invalidIndexes.
Add Email Addresses
POST /api/v1/leads/:leadId/emails · Scope: contacts:update
Same behavior as phones.
{ "success": true, "contactId": "uuid-...", "totalEmails": 2 }
Update Contact
PATCH /api/v1/contacts/:contactId · Scope: contacts:update
Accepts firstName, lastName, fullName, phonePrimary, emailPrimary, mailingAddress, age.
Owner-identity guard. Foreclosure data frequently carries the name of a law firm, trustee, or loan servicer rather than the property owner. If the resulting name looks like a non-owner entity, the name fields are silently not applied, and any
phonePrimaryoremailPrimarysent in the same request is dropped with it, on the basis that those channels belong to the rejected party. A channel-only patch with no name fields is always applied. The response is200either way, so re-read the contact if you need to confirm the write landed.
{ "success": true, "contactId": "uuid-..." }
Per-Number DNC
POST /api/v1/leads/:leadId/phone-dnc · Scope: contacts:update
Blocks or unblocks one number on one channel. This is the per-number suppression you read back from Get Lead, and it is separate from the contact-wide dncSms / dncVoice flags.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/phone-dnc \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "phone": "6145551234", "channel": "sms", "blocked": true }'
| Field | Required | Notes |
|---|---|---|
phone | yes | Must already be on this lead's contact. Matched on the bare digits, so formatting does not matter. |
channel | yes | "sms" or "voice". A number can be blocked on one and open on the other. |
blocked | yes | true blocks, false attempts a release. |
Blocking is unconditional and idempotent:
{ "success": true }
Releasing is not. The API can never clear a consumer opt-out, so a release only lifts holds an integration is allowed to lift, then re-reads the number and tells you the truth:
{
"success": false,
"removed": 0,
"optOutHold": true,
"platformHold": false,
"message": "This number is on the opt-out list (usually from a STOP or similar reply). An admin can remove it only after the contact agrees to hear from you again."
}
A clean release returns success: true with removed and clearedUnreachableProbation.
Notes
success: falseon a release is a200, not an error. It means the number is still blocked and names what is holding it. Check the field rather than the status code.- An API key can never release an opt-out. Releasing one is a compliance decision that requires an admin or manager to attest that the contact re-consented, and API keys carry no actor role.
confirmOptOutReleaseis rejected on this path. - A
platformHold(litigator or DNC registry match, or a platform-level block) cannot be cleared by anyone through this endpoint. - Blocking a number your own suppression list already covers is safe to re-send on every sync.
- This does not stop a running campaign by itself, though a cadence with no remaining deliverable channel will stop sending. To halt outreach on a lead, use Pause Cadences.
| Status | Meaning |
|---|---|
400 | phone missing, or channel is not "sms" or "voice" |
404 | Lead not found, it belongs to another organization, or the number is not on this lead's contact |
List Notes
GET /api/v1/leads/:leadId/notes · Scope: leads:read
Returns every note on the lead's Notes tab, oldest first: notes added in the app, through this API, by imports, and AI call summaries. If the lead was merged into another lead, this returns the notes of the lead it was merged into, and leadId in the response says which.
{
"success": true,
"leadId": "uuid-...",
"notes": [
{ "id": "uuid-...", "leadId": "uuid-...", "note": "Left voicemail", "author": "Jane Smith", "userId": "uuid-...", "isAi": false, "subtype": null, "createdAt": "2026-11-23T15:04:05.000Z" }
]
}
| Status | Meaning |
|---|---|
404 | Lead not found, or it belongs to another organization |
Add Note
POST /api/v1/leads/:leadId/notes · Scope: leads:update
Adds a note to the lead's Notes tab, exactly as if the API key's user had typed it there, and logs it on the lead's activity timeline. This does not overwrite the lead's notes field, which is a separate single value edited via Update Lead. A note is at most 50,000 characters; surrounding whitespace is trimmed. If the lead was merged into another lead, the note is saved on the lead it was merged into, and leadId in the response says which.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/notes \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-d '{ "note": "Left voicemail, callback requested Tuesday" }'
Response 201
{ "success": true, "noteId": "uuid-...", "activityLogId": "uuid-...", "leadId": "uuid-...", "note": { "id": "uuid-...", "note": "Left voicemail, callback requested Tuesday" } }
Keep noteId to edit or delete the note later.
| Status | Meaning |
|---|---|
400 | note missing, empty, or longer than 50,000 characters |
404 | Lead not found, or it belongs to another organization |
Edit Note
PATCH /api/v1/leads/:leadId/notes/:noteId · Scope: leads:update
Replaces a note's text. Body: { "note": "new text" }. A merged lead's id works here too: it reaches the notes on the lead it was merged into. The Notes tab's rules apply, with the API key's user as the person editing: a key can edit notes its user wrote (including notes it added through this API), and an admin's key can also edit imported notes. Nobody can edit a teammate's note or an AI call summary.
Response 200: { "success": true, "note": { ... } }
| Status | Meaning |
|---|---|
400 | note missing, empty, or longer than 50,000 characters |
403 | The key's user is not allowed to edit this note |
404 | Note not found on this lead in your organization |
Delete Note
DELETE /api/v1/leads/:leadId/notes/:noteId · Scope: leads:update
Deletes a note permanently. A key can delete notes its user wrote; an admin's key can also delete a teammate's note or an imported note. AI call summaries and other system notes cannot be deleted.
Response 200: { "success": true, "deleted": true, "noteId": "uuid-..." }
| Status | Meaning |
|---|---|
403 | The key's user is not allowed to delete this note |
404 | Note not found on this lead in your organization |
Document Endpoints
Both document endpoints additionally require the key's user to hold the api:upload_documents permission. See Additional permission checks.
Upload Documents
POST /api/v1/leads/:leadId/documents · Scope: documents:upload
Multipart upload, up to 10 files per request, 25 MB each.
curl -X POST https://<your-domain>/api/v1/leads/LEAD_ID/documents \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-F "files=@contract.pdf" \
-F "files=@photos.zip" \
-F "category=contract" \
-F "notes=Signed purchase agreement"
| Form field | Notes |
|---|---|
files | Repeatable. This exact field name is required. |
category | Defaults to other |
notes | Optional free text |
Allowed extensions: .pdf, .doc, .docx, .xls, .xlsx, .csv, .txt, .jpg, .jpeg, .png, .gif, .webp, .heic, .tif, .tiff, .bmp.
Response 200
{
"success": true,
"documents": [
{ "id": "uuid-...", "fileName": "contract.pdf", "category": "contract", "fileUrl": "..." }
]
}
List Documents
GET /api/v1/leads/:leadId/documents · Scope: documents:read
Returns all documents on the lead, newest first.
{ "success": true, "documents": [ { "id": "uuid-...", "fileName": "contract.pdf", "...": "..." } ] }
Foreclosure Endpoints
Update Auction
POST /api/v1/foreclosure/update-auction · Scope: foreclosure:update
Updates an existing auction tracking record, matched on case number plus county. It does not create leads.
| Field | Required | Notes |
|---|---|---|
caseNumber | yes | Case-insensitive match |
county | yes | Normalized before matching |
auctionDate | no | Written to the foreclosure record |
openingBid | no | Written to auction tracking |
curl -X POST https://<your-domain>/api/v1/foreclosure/update-auction \
-H "Authorization: Bearer pfp_YOUR_KEY_HERE" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: auction-2026-03-25-001" \
-d '{ "caseNumber": "2025CV001234", "county": "Franklin", "auctionDate": "2026-04-15", "openingBid": 125000 }'
Response 200
{ "success": true, "action": "updated", "auctionTrackingId": "uuid-...", "leadId": "uuid-..." }
Response 404 — no tracking record exists yet:
{ "success": false, "message": "No auction tracking found for this caseNumber+county. Create a lead first." }
Supports Idempotency-Key.
Update Upset Bid
POST /api/v1/foreclosure/update-upset-bid · Scope: foreclosure:update
Records an upset bid and moves the auction into the upset period.
| Field | Required |
|---|---|
caseNumber, county | yes |
upsetBid, upsetDeadline, bidder, bidderPhone | no |
{
"success": true,
"auctionTrackingId": "uuid-...",
"leadId": "uuid-...",
"upsetCount": 2,
"currentBidAmount": 131250
}
Notes
auctionStatusis set toupset_period.- A bid is appended to the record's bid history when
upsetBidis present. upsetCountincrements on every call, including calls that send noupsetBid. Only call this endpoint when an upset bid has actually been recorded, or your counts will drift.
Foreclosure Lookup
GET /api/v1/foreclosure/lookup · Scope: leads:read
Requires both caseNumber and county query parameters, otherwise 400.
{
"success": true,
"found": true,
"leadId": "uuid-...",
"auctionTrackingId": "uuid-...",
"auctionDate": "2026-04-15T00:00:00.000Z",
"auctionStatus": "upcoming",
"openingBid": 125000,
"upsetBid": null,
"upsetCount": 0
}
Auction Watchlist
GET /api/v1/foreclosure/watchlist · Scope: leads:read
Every tracked auction with a date between now and days from now.
| Query param | Default |
|---|---|
days | 30 |
{
"success": true,
"count": 12,
"watchlist": [
{
"auctionTrackingId": "uuid-...",
"leadId": "uuid-...",
"caseNumber": "2025CV001234",
"county": "Franklin",
"auctionDate": "2026-04-15T00:00:00.000Z",
"auctionStatus": "upcoming",
"openingBid": 125000,
"upsetBid": null,
"upsetDeadline": null,
"upsetCount": 0,
"address": "123 Main St",
"city": "Columbus",
"state": "OH",
"zip": "43215"
}
]
}
Sorted by auction date, soonest first.
Stats Endpoints
Lead Stats
GET /api/v1/stats/leads · Scope: stats:read
Counts across your whole organization, excluding archived and merged leads.
{
"success": true,
"prospects": 4210,
"leads": 812,
"opportunities": 96,
"deals": 14,
"byStatus": { "prospect": 4210, "lead": 812, "opportunity": 96, "closed_won": 11 },
"byCounty": { "Franklin": 1204, "Cuyahoga": 890 },
"byAuctionMonth": { "2026-04": 33, "2026-05": 51 }
}
deals is the sum of closed_won, closed_rental, and closed. byAuctionMonth counts auction tracking records, not leads.
Activity Report
GET /api/v1/reports/activity · Scope: reports:read
The numbers on the Activity Report page (Reports, Activity Report) for a date range: calls, texts, emails, video texts and doorknocks by channel, by day and by team member, plus call connect rate, text response rate and email open rate. The same range and filters return the same numbers as the page.
| Query parameter | Required | Meaning |
|---|---|---|
startDate, endDate | yes | ISO 8601 timestamps, for example 2026-10-01T00:00:00Z. At most 92 days apart. |
compareStartDate, compareEndDate | no | A second range to compare against, same rules. Give both or neither. Adds comparison and deltas to the response. |
agentId | no | Only activity by this team member (user id). |
source | no | Only activity on leads with this lead source. |
county, state | no | Only activity on leads whose property is in this county or state. |
Each filter is given once, as text, up to 200 characters.
{
"success": true,
"current": {
"channelCounts": { "cell_calls": 12, "crm_calls": 140, "manual_texts": 85, "auto_texts": 2310, "manual_emails": 4, "auto_emails": 0, "video_texts": 0, "doorknocks": 0 },
"channelLabels": { "cell_calls": "Cell Phone Calls", "crm_calls": "CRM Calls", "manual_texts": "Manual Texts", "auto_texts": "Auto Texts", "manual_emails": "Manual Emails", "auto_emails": "Auto Emails", "video_texts": "Video Texts", "doorknocks": "Doorknocks" },
"totalActivities": 2551,
"dailyActivity": [{ "date": "2026-10-01", "crm_calls": 9, "auto_texts": 120, "total": 129 }],
"agentActivity": [{ "userId": "8f0c…", "agentName": "Sam Rivera", "crm_calls": 140, "manual_texts": 85, "total": 225 }],
"qualityMetrics": {
"totalCalls": 152, "connectedCalls": 61, "connectRate": 40.13,
"qualityConversations": 18, "qualityConversationRate": 11.84, "avgCallDuration": 94,
"outboundTexts": 2395, "textResponseRate": 6.3,
"totalEmails": 4, "emailOpenRate": 50
},
"heatmapData": [{ "dayOfWeek": 2, "hour": 15, "count": 37 }],
"inboundOutbound": { "inbound": 160, "outbound": 2391 }
},
"comparison": null,
"period": { "startDate": "2026-10-01T00:00:00.000Z", "endDate": "2026-10-31T23:59:59.999Z" }
}
- Rates are percentages rounded to two decimals.
avgCallDurationis in seconds, over calls that connected. A quality conversation is a call longer than 2 minutes. textResponseRatecounts an outbound text as answered when the lead texted back later within the same range and filters. A reply afterendDate, or one outside anagentIdfilter, does not count.dailyActivitydates are UTC days. A channel with no activity that day is left out of the day's object.agentActivityuses"unassigned"as theuserIdfor activity with no team member.totalActivitiesalso counts internal records the channels leave out, such as notes, so it can be higher than the sum ofchannelCounts.- With a comparison range,
comparisonhas the same shape ascurrent(withoutagentName), anddeltascompares the two: counts as a percentage change (50means 50% more), and the three rates (connectRateDelta,textResponseRateDelta,emailOpenRateDelta) as the difference in percentage points (50% to 75% is25). A delta isnullwhen the earlier value was 0.
Limits. Besides your key's per-minute limit, this report allows 10 requests per minute per key, because it reads every message in the range. Over that, it returns 429 with a Retry-After header. A range longer than 92 days, a missing date, or a filter given twice returns 400 with a message saying which.
Inbound Webhooks
Inbound webhooks are the no-code path into Foresight. You create a token URL in the UI and point Zapier, Make, a PPC landing page, or Facebook Lead Ads at it. No API key and no bearer token are involved.
Create one under Settings → Incoming webhooks. The URL looks like:
POST https://<your-domain>/api/v1/webhooks/inbound/<64-hex-token>
Copy the URL when it is created. The full token is shown once.
Request
Any JSON object. Field names are mapped automatically, so you can usually point a form at it without configuring anything.
| Incoming key | Maps to |
|---|---|
full_name, fullName | Full name, split into first and last |
first_name, firstname, first | First name |
last_name, lastname, last | Last name |
email, email_address, emailaddress | |
phone_number, phone, phonenumber, mobile, mobile_number | Phone, normalized to 10 digits |
street_address, street, address | Street address |
city, state | City, state |
zip_code, zip, postal_code, zip_postal_code, zipcode | ZIP |
distress_type, distresstype, lead_type | Distress type |
any key containing lot_size or acreage | Lot size, and the property is tagged as Land |
lead_source, leadSource | Lead source for this one lead (see below) |
Unrecognized keys are passed through under their original name. country, job_title, and company_name are accepted and ignored.
Lead source. Every lead gets the source label set on the webhook under Settings → Incoming webhooks. When one webhook carries several providers, send lead_source (for example "sellers direct") and that lead gets it instead. It is lowercased and capped at 100 characters. Two limits: a lead_source can never make a lead count as a raised-hand inbound source (Facebook, Google, web form and similar) or skip the SMS opt-out line when the webhook's own label would not, so on a cold webhook it is ignored in those cases and the webhook label is used. A field named source is not read.
Minimum viable payload: at least one of an email, a phone, a name, or a street address. Anything less is rejected.
curl -X POST https://<your-domain>/api/v1/webhooks/inbound/YOUR_TOKEN \
-H "Content-Type: application/json" \
-d '{
"full_name": "Jane Doe",
"phone_number": "(614) 555-1234",
"email": "jane@example.com",
"street_address": "123 Main St",
"city": "Columbus",
"state": "OH",
"zip_code": "43215"
}'
Response
201 when a lead was created, 200 when an existing lead was matched and updated.
{
"success": true,
"action": "created",
"leadId": "uuid-...",
"propertyId": "uuid-...",
"contactId": "uuid-...",
"matchedBy": null,
"duration_ms": 68
}
Classification
Each webhook is configured as one of two types, and this choice controls whether automated outreach is allowed.
| Classification | Lead status | Automated outreach | Use for |
|---|---|---|---|
inbound_raised_hand | Forced to lead | Allowed. Triggers Speed to Lead and a new-lead alert on creation. | Someone filled out your form |
cold_import | Left as-is | Not started. | Purchased lists, scraped data |
A re-fired inbound_raised_hand webhook can promote a prospect to a lead, but never downgrades a lead a rep has already advanced.
Errors
| Status | Meaning |
|---|---|
400 | Body missing, empty, or not a JSON object |
401 | Token missing, malformed, or unknown. The token must be exactly 64 lowercase hex characters. |
403 | Webhook is disabled. Re-enable it under Settings → Incoming webhooks. |
422 | No usable contact or address data, or the row failed to import |
429 | More than 30 requests per minute for this token. Honor the Retry-After header. |
500 | Internal processing error. Safe to retry. |
A 422 for missing data includes a hint:
{
"success": false,
"error": "No usable contact or address data found",
"hint": "Include at least one of: email, phone_number, full_name/first_name+last_name, or street_address+city+state+zip_code"
}
Duplicate delivery
Deliveries are deduplicated automatically. If the same event is delivered twice you get 200 with duplicate: true rather than a second lead:
{ "success": true, "duplicate": true, "leadId": "uuid-..." }
A 202 with duplicate: true means the first delivery is still being processed. Every delivery, successful or not, is logged with its payload summary, IP, and duration under Settings → Incoming webhooks.
Outgoing Webhooks
Outgoing webhooks are the other direction: Foresight sends a POST to your URL when something happens on a call, so your system does not have to poll. Set them up under Settings → Outgoing webhooks (people who can manage API keys). Each account can have up to 10.
Events
| Event | Sent when |
|---|---|
call.completed | A dialer or AI call ends. Sent once per call, about a minute after it ends. |
call.note | A rep adds, edits or clears the note on a dialer call. data.action is added, updated or cleared. |
webhook.test | You click Send test in Settings. |
Body
{
"id": "evt_6c0f…",
"type": "call.completed",
"createdAt": "2026-11-05T15:04:05.000Z",
"organizationId": "…",
"data": { "callId": "…", "source": "dialer", "leadId": "…" }
}
id stays the same on every retry of an event, so use it to skip repeats. With Include call details turned on for the endpoint, data.call carries the call in the same shape as Get Call, including its lead block, read when the message is sent, and a call.note event adds data.note.text. It never carries transcript. With it off, fetch the call with GET /api/v1/calls/:callId?source=<source>.
Headers and signature
| Header | Value |
|---|---|
Foresight-Event | The event type |
Foresight-Delivery | The event id |
Foresight-Signature | t=<unix seconds>,v1=<hex HMAC-SHA256> |
v1 is the HMAC-SHA256, keyed with your endpoint's signing secret (shown once when you create the endpoint), of the string <t>.<raw request body>. Check it before trusting a message, compare in constant time, and reject a t more than 5 minutes from your clock:
const crypto = require("crypto");
// rawBody: the request body exactly as received (a string or Buffer), before any JSON parsing.
function verify(rawBody, header, secret) {
const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
if (!match) return false;
const [, t, v1] = match;
if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest();
return crypto.timingSafeEqual(expected, Buffer.from(v1, "hex"));
}
Delivery rules
- Only
https://URLs. Addresses that resolve to private or reserved networks are refused. - Answer with any
2xxwithin 10 seconds. Anything else, including a redirect, counts as a failure; redirects are never followed. - A failed event is retried after 1 minute, 5 minutes, 15 minutes, 1 hour, 3 hours, 6 hours and 12 hours, then given up.
- An endpoint with no successful delivery for 24 hours is paused, and the account's admins are told in the app and by email. Resume it in Settings once it is fixed. Events from while it was paused are not sent; fetch those calls with List Calls.
call.completedonly covers calls that ended after the endpoint was created, resumed, or hadcall.completedticked.- Events can arrive out of order, and rarely more than once. Use
idto skip repeats andcreatedAtto order them.
Error Codes
| Error Code | HTTP Status | Description |
|---|---|---|
FORBIDDEN | 403 | API key lacks import:run scope or api:import_leads permission |
COUNTY_TRIAL_EXPORT_BLOCKED | 403 | Organization is on a County Data trial with delivered leads. See County Data trial restriction. |
UNSUPPORTED_SCHEMA_VERSION | 400 | schema_version not in supported list (currently only "1.0") |
INVALID_FLAGS | 400 | Conflicting flags (e.g. both update_only and create_only) |
INVALID_FORMAT | varies | Field validation failure (e.g. ZIP must be 5 or 9 digits, auctionDate must be a valid date). Returned per-row with action: "failed" and the offending field name. |
MISSING_FIELD | 400 | Required lookup parameters not provided |
VALIDATION_FAILED | 400 | No rows provided, CSV parse error, or invalid body format |
BATCH_TOO_LARGE | 400 | Row count exceeds max_batch_size (default 5,000) |
STRICT_ABORT | 400 | A row failed in strict mode — entire transaction rolled back |
NOT_FOUND | varies | No matching property found for update_only / PATCH (per-row), or job ID not found (job endpoints return 404) |
IN_PROGRESS | 409 | A request with this idempotency key is already being processed |
PROPERTY_LOCKED | 409 | Another import is currently processing this property — retry shortly |
RATE_LIMIT_EXCEEDED | 429 | Too many requests — wait for the window to reset |
CONCURRENCY_LIMIT_EXCEEDED | 429 | Too many requests in progress for this key or the platform. Wait Retry-After seconds (2) and retry |
INTERNAL_ERROR | 500 | Unexpected server error |
Lead tiers
Each organization has three ordered tiers with editable names. Defaults are generic. Tune the numbers to your market. Tier tags are managed by the platform; your own tags are never touched.
| Endpoint | Authorization | Result |
|---|---|---|
GET /api/v1/settings/lead-tiers | leads:read or leads:update | { success, enabled, tiers, updatedAt, counts } |
PUT /api/v1/settings/lead-tiers | leads:update | Saved config, paused, and optional retiered: { evaluated, changed, remaining } |
POST /api/v1/lead-tiers/retier | leads:update | { success, evaluated, changed, remaining }: marks every earlier evaluation stale, evaluates up to 5,000 within a 20-second budget; repeat calls continue where the last stopped and the hourly sweep finishes the rest |
GET /api/lead-tiers | Signed-in session | Current config and counts |
POST /api/lead-tiers/preview | Signed-in session | Proposed config's { tier_1, tier_2, tier_3, unrated } counts, without saving |
PUT /api/lead-tiers | Admin session | Same settings body and result as the public PUT |
POST /api/lead-tiers/retier | Admin session | { evaluated, changed, remaining }, same batching as the API route |
Example PUT body (omit outreachTiers to leave the current Outreach approval gate as it is):
{
"enabled": true,
"tiers": [
{ "key": "tier_1", "name": "Tier 1", "rules": {
"minEquity": 100000, "maxLtv": 65, "excludeLlcOwned": true,
"propertyTypeExclude": ["condo"],
"locations": {
"include": [
{ "kind": "county", "value": "Broward County", "state": "FL", "fips": "12011" },
{ "kind": "zip", "value": "33009" }
],
"unknownLocation": "fail"
}
} },
{ "key": "tier_2", "name": "Tier 2", "rules": {
"minEquity": 50000, "maxLtv": 80,
"locations": { "include": [{ "kind": "state", "value": "FL" }] }
} },
{ "key": "tier_3", "name": "Tier 3", "rules": {} }
],
"locationsAware": true,
"outreachTiers": ["tier_1", "tier_2"],
"pauseNonMatchingNow": false,
"retierNow": true
}
tiers must contain exactly tier_1, tier_2, tier_3 in that order, with names of 1-40
characters. Every rule is optional:
| Rule | Meaning |
|---|---|
minEquity, maxEquity | Inclusive equity bounds in dollars |
minLtv, maxLtv | Inclusive loan-to-value bounds in percent |
minValue | Minimum property zestimate in dollars |
propertyTypeExclude, propertyTypeInclude | String arrays; case-insensitive substring matches against property type |
excludeLlcOwned | When true, ownership must be explicitly non-LLC |
auctionWithinDays | Future auction within this many days, inclusive |
distressTypes | Exact allowed lead.distressType values from the lead taxonomy |
locations | Market restriction: { include, exclude, unknownLocation }. A lead in any ONE include entry passes; an empty or absent include does not restrict. A lead in any exclude entry fails the tier outright. |
Each location entry is { kind, value, state?, fips? } where kind is zip, city, county
or state. A zip is 5 digits. A city and a county each require state; a state entry
and a zip entry must not carry one. A county is identified by its 5-digit Census fips
and must carry it, because a county name alone can mean more than one place (Baltimore County
and Baltimore City in MD; Rio Grande in both CO and PR). Entries are normalized on save, so the
stored value is the Census name. A lead's county comes from the parcel record, or from its zip
where that zip lies in a single county. unknownLocation is "fail" (default) or "pass" and
decides only leads whose location cannot be determined at all, never a lead whose location is
known and simply not on the list.
locationsAware: true declares that the caller can see market restrictions. A PUT that would
delete markets already saved on a tier is refused with 409 unless it is set, because this
endpoint replaces the whole config and an older integration would otherwise wipe an operator's
market lists silently. Send the current rules.locations back (GET then PUT) to keep them, or
pass locationsAware: true to clear them deliberately. The 409 body names the affected tiers.
Numeric rules must be finite and nonnegative. Tiers are evaluated in order; every specified
rule must pass. Missing required input fails that tier. An empty rules object is a catch-all
for remaining leads with a property record. A lead without a property record, a disabled
config, or no matching tier produces unrated and removes this engine's prior tier claim.
Canonical foreclosure data supplies equity, LTV, LLC ownership, and auction date. When equity
is absent, zestimate minus estimated loan balance supplies it. When LTV is absent and value
is positive, estimated loan balance / zestimate * 100 supplies it. Both fallback inputs must
be present; the engine never guesses a missing value.
outreachTiers writes the P4 Outreach approval gate. Selecting all three writes mode: "off".
Any subset writes mode: "allow_tags" with those tier keys. An empty subset holds all automated
outreach. Pausing outreach that is already running is opt-in: pass pauseNonMatchingNow: true
to pause automated enrollments on leads outside the selected tiers (operator pauses and manual
enrollments are never touched). This save does not resume gate-paused enrollments; the Outreach
approval gate endpoint controls that separately.
retierNow: true evaluates up to 5,000 stale leads in this call, within a 20-second budget and
before the gate's pause pass, and returns evaluated, changed, and remaining. Every save
marks earlier evaluations stale, so the hourly sweep finishes what one call did not; calling
retier again continues rather than restarting. Turning tiers off retracts the platform's tier
tags the same way without retierNow. GET and preview return counts: null above 100,000 org
leads.
Preview counts use the proposed rules, not the currently stored tier tags.
Imports and lead creation await best-effort tier evaluation before automatic enrollment.
Financial PATCH fields (estEquity, estLoanBalance, ltvRatio, auctionDate, openingBid)
also trigger evaluation, including supplied zero or null values. An evaluation failure is
logged and does not fail the import or update. County-feed upserts evaluate inside the import
transaction before routing. The hourly scheduler evaluates at most 2,000 stale leads fleet-wide
under one advisory lock: never-evaluated leads first (oldest first), then evaluations older
than the org's settings or the lead's own row, and, for orgs whose rules use
auctionWithinDays, auction-dated leads at least daily. Merged, archived, and demo leads are
excluded; an org with tiers switched off takes part only while its leads still carry a tier
tag. Changes to financial or property inputs clear the evaluation timestamp through database
triggers that skip a lead row another writer holds. Saving settings makes older evaluations
stale. Unchanged import rows and enrichment writes are covered by this sweep. Setting
LEAD_TIERS=off on the server stops the sweep and the write-path hooks fleet-wide; explicit
retier calls still work. Note that the import fingerprint ignores estEquity,
estLoanBalance, ltvRatio, and isLlcOwned, so re-importing an otherwise identical row that
changes only those is skipped as unchanged; update them on an existing lead with PATCH.
GET /api/v1/leads/:leadId adds lead.tier, derived from an exact tier tag and that org's names:
{ "lead": { "tier": { "key": "tier_1", "name": "Tier 1" } } }
The value is null when no tier tag is present. Tier 1/2/3 saved views on both Prospects and
Leads filter their exact tier_1/tier_2/tier_3 tags. Tier claims use provider tier_engine;
claims and tags from other providers, including operator tags such as gold, are preserved.
Per-Row Result Actions
Each row in a batch (or single-row) response includes an action field describing what happened:
| Action | Success | Description |
|---|---|---|
created | true | New property, lead, and contact were created |
updated | true | Existing record was matched and updated with new data |
skipped | true | Record matched but import hash is unchanged — no writes performed |
already_exists | true | Record matched and create_only flag is set, or duplicate within the same batch (matchedBy: "batch_dedup") |
not_found | false | update_only flag is set but no existing record matched — returns error_code: "NOT_FOUND". Single-row endpoints return HTTP 404 without an action field; batch job rows include action: "not_found". |
skipped_locked | — | Property is locked by another concurrent import — retry later (batch only) |
failed | false | Row processing failed (see error_code and error fields) |
Merge Behavior on Update
When a record is updated:
- Property fields are merged: incoming non-empty values overwrite existing values. Empty incoming values are ignored unless
overwrite_empty: true. - Contact fields follow the same merge logic.
- Foreclosure fields follow the same merge logic.
- The fields
address,firstName,lastName, andfullNameare non-nullable — ifoverwrite_emptyis true and the incoming value is empty, they are set to""rather thannull.