# Indax Products API (search and chat): full documentation
> Your catalog search and Dax, the Indax assistant, on your own website. Source: https://indax.co/docs/products-api
---
# Products API
> Your catalog search and Dax, the Indax assistant, on your own website.
Indax indexes a company's public website (products, parts, pages and PDFs). Two endpoints put it on your site: **search**, which answers typically in under 200 ms, and **chat**, where Dax, the Indax assistant, answers from the same catalog. You build the interface; Indax runs the index and the assistant.
| Endpoint | What it does |
| --- | --- |
| [`POST /v1/search`](/docs/products-api/search) | Products, parts, pages and PDFs for a query, best first, each linking to the company's own page. |
| [`/v1/chat`](/docs/products-api/chat) | Dax answers from the catalog, word by word. WebSocket, or Server-Sent Events over `POST`. |
Base URL `https://api.indax.net` · Auth `Authorization: Bearer indax_live_…` · [OpenAPI spec](https://api.indax.net/v1/openapi.yaml)
## Good to know
- **Your key is your company.** It bills your Indax credits: 1 per search, 1 or more per chat turn.
- **Any company on the Indax network:** pick one with `domain`, e.g. `"mpechicago.com"`. Default: your own.
- **Public data only.** The API reads the public website, never your email, CRM or ERP.
## Start
1. [Quickstart](/docs/products-api/quickstart): a key, a search and a chat in 5 minutes.
2. Replacing a site search? [Replace your site search](/docs/products-api/site-search) maps search boxes, results pages, filters and analytics to the API.
3. Try every parameter live on [Search](/docs/products-api/search) and [Chat](/docs/products-api/chat).
4. Building with an AI agent? Give it [this page](/docs/products-api/for-agents) or [llms-full.txt](/docs/products-api/llms-full.txt).
---
# Quickstart
> A key, a first search and a first chat in 5 minutes.
## 1. Get a key
In the [Indax app](https://app.indax.co/developers), open **API** and select **Create key**. Choose **Products**, give it a name, and copy the key. You see it once.
```bash
export INDAX_KEY=indax_live_...
```
Calling from browser code? Add your site under **Allowed websites** (e.g. `https://www.example.com`). Leave it empty for a server-only key.
## 2. Search
```bash
curl https://api.indax.net/v1/search \
-H "Authorization: Bearer $INDAX_KEY" \
-H "Content-Type: application/json" \
-d '{"q": "grinder for activated carbon", "limit": 3}'
```
You get `results`, each with a `type`, `title`, `url` (link to it), `summary` and `image`. Paste your key above any playground on these pages to run it here instead.
## 3. Chat
```bash
curl -N https://api.indax.net/v1/chat \
-H "Authorization: Bearer $INDAX_KEY" \
-H "Content-Type: application/json" \
-d '{"text": "Which grinder fits activated carbon?"}'
```
The answer streams as `data:` lines: `delta` pieces of text, then `results` (the pages Dax used), then `done`. For a chat window in the browser, use the [WebSocket](/docs/products-api/chat#websocket).
## 4. Check usage
**Usage** in the Indax app shows API search and API chat credits, one row per key.
---
# Replace your site search
> What a site search or advanced search needs, and which part of the API does each.
This page is for the team building the website: what to build, what the API already does, and what stays yours. Indax keeps the index up to date from the company's public website (products, parts, pages and PDFs), so there is nothing to upload or sync.
## What the API does, what you build
| On the site | With the API | You build |
| --- | --- | --- |
| Search box, keywords, part and model numbers | `POST /v1/search` with what the visitor typed in `q`. An exact part or model number comes first. | The box and the results layout |
| Suggestions while typing | The same call with `limit: 5`, 250 ms after the last key, 2+ characters | The dropdown |
| Results page with tabs (Products, Parts, Pages, Documents) | Each result has a `type`. One call per tab with `types`, or one call and group by `type`. | The tabs |
| Filters (category, brand, certification, specs) | `facets: true` returns the values with counts; send one chosen value per filter back in `filters` | The filter panel |
| Paging | `next_cursor` → `cursor`, up to 100 results per query | Pager or "load more" |
| Ranking by the page the visitor is on | `context` with the page URL and the visit's trail. See [Page context](/docs/products-api/page-context). | Two lines of script |
| Questions in plain language ("which grinder for coffee?") | `/v1/chat`: Dax answers from the same catalog and lists the pages it used | The chat window |
| Analytics | Not sent anywhere by Indax | Your own events (below) |
Not in the API: sorting other than by relevance, and search over anything that is not on the public website (CRM, ERP, email).
## Choose where the calls come from
| | From the browser | Through your server |
| --- | --- | --- |
| Key | A **website key** listing your sites (production and staging) | A **server-only key**, kept in an environment variable |
| Pros | No back end to run; fastest | Key never in page code; you can cache, log and add `instructions` to chat |
| Chat | WebSocket from the page | `POST /v1/chat` (Server-Sent Events), streamed on to the page |
Both work. A browser key is safe to expose: it only works from the sites listed on it, and it is rate limited. Use one key per environment, so staging can be revoked alone. See [Keys and credits](/docs/products-api/authentication).
## A results page in one call
```js
const res = await fetch("https://api.indax.net/v1/search", {
method: "POST",
headers: { Authorization: `Bearer ${INDAX_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
q: params.get("q"),
limit: 20,
facets: true,
filters: chosenFilters, // one value per filter, e.g. { category: "Coffee Grinding Equipment" }
cursor: params.get("page") || undefined, // next_cursor from the previous page
context: window.indaxContext?.(), // optional, see Page context
}),
});
const body = await res.json();
if (!res.ok) return showFallback(body.message); // see Errors and limits
render(body.results, body.facets, body.next_cursor, body.total);
```
Each result links to the company's own page (`url`). Show `image`, `title`, `summary`, and for products and parts `part_number`, `brand` and up to 4 `specs`.
## Analytics
Indax does not send events to your analytics. Record searches where you already do, for example your analytics tool's site-search event with the query and the result count, and a click event with the result's `url`. Each response's `id` (and the `x-request-id` header) identifies the request if you need to ask Indax about one. Credits per key are under **Usage** in the Indax app.
## When the API is unavailable
Errors come back as JSON with a `message` that is safe to show. On `402`, `429` and `5xx`, show the message with a link to your contact page or catalog, so the visitor is never stuck. See [Errors and limits](/docs/products-api/errors-and-limits) for codes and a retry helper.
## Launch checklist
- [ ] A key per environment; the website key lists every production and staging domain (with and without `www`).
- [ ] Searching a known product name and a known part number returns it first.
- [ ] Filters narrow the results and paging shows no duplicates.
- [ ] Suggestions are debounced (250 ms, 2+ characters).
- [ ] The error state shows a message and a way to contact sales.
- [ ] Searches and result clicks reach your analytics.
- [ ] Chat (if used) streams, keeps follow-ups, and resumes after a reload.
---
# Search
> POST /v1/search returns products, parts, pages and PDFs for a query.
Type and the results update: every change calls the live API. Click a facet to filter. **Code** shows the exact request and response.
## Request
Only `q` is required.
| Field | Type | Default | What it does |
| --- | --- | --- | --- |
| `q` | string, 1–200 chars | required | What the visitor typed: a part number, a product type, a material, a question. Any language. |
| `domain` | string, or up to 20 | your company | The company to search, by website domain. Several are interleaved; each result says its `company`. |
| `types` | `products` `parts` `pages` `documents` | all | Only these kinds of results. |
| `limit` | 1–50 | 10 | Results per page. |
| `cursor` | string | | `next_cursor` from the previous response. |
| `filters` | `{ category, brand, cert, specs }` | | Products and parts only. Values come from `facets`. Every filter must match. |
| `facets` | boolean | `false` | Also return the filter values the results offer, with counts. |
| `context` | object | | Where the visitor is on your site. See [Page context](/docs/products-api/page-context). |
| `boost` | boolean | `true` | Let `context` move matching results up. |
Header `x-request-id` (8–100 chars) traces a request; a retry with the same id is charged once.
## Response
```json
{
"id": "req-7f2a9c1e",
"results": [
{
"id": "1b0fbd7a-…",
"type": "product",
"company": "mpechicago.com",
"title": "Activated Carbon Grinder",
"url": "https://www.mpechicago.com/activated-carbon-grinder/",
"summary": "Grinds activated carbon into uniform particle sizes…",
"image": "https://www.mpechicago.com/…/grinder.jpg",
"part_number": null,
"category": "Granulizers",
"brand": "mpe",
"certs": [],
"specs": [{ "name": "Capacity", "value": "500–2,000 lb/hr" }]
}
],
"next_cursor": "10",
"total": 23,
"facets": { "category": [{ "value": "…", "label": "…", "n": 4 }], "brand": [], "cert": [], "specs": [] },
"context_applied": false,
"credits_used": 1,
"timing": { "search_ms": 92, "total_ms": 104 }
}
```
| Field | What it is |
| --- | --- |
| `results[].type` | `product`, `part`, `page` or `document` (a PDF). |
| `results[].url` | The company's own page or file. Link to it. |
| `results[].summary` | A short passage; for pages, the part that matches the query. |
| `results[].page_kind` | Pages and documents: `application`, `blog`, `docs`, `category`, `product`, `contact`, `file`, `other`. |
| `brand`, `certs`, `specs` | Products and parts: for cards and comparison tables (up to 12 specs). |
| `next_cursor` | Send as `cursor` for the next page; `null` on the last. Up to 100 results per query. |
| `facets` | With `facets: true`. Send `category` and `cert` back by `label`, `brand` by `value`, `specs` as `{ key: values[].label }`. |
| `context_applied` | `true` when page context changed the order. |
## Tips
- Send exactly what the visitor typed. Use `types` and `filters`, not extra words in `q`.
- An exact model or part number (`GPC-140`) comes first.
- Search as you type: wait 250 ms after the last key and send 2+ characters. Each search is 1 credit.
---
# Chat
> Dax answers visitors from the catalog, word by word. Server-Sent Events or WebSocket.
Ask Dax a question and watch the answer stream. Follow-ups keep the conversation. **Code** has the request and every frame the API sent.
## Two ways to connect
| | `POST /v1/chat` (Server-Sent Events) | `wss://api.indax.net/v1/chat` (WebSocket) |
| --- | --- | --- |
| Best for | Servers, one-off turns, the playground above | A chat window in the browser |
| Auth | `Authorization: Bearer` header | `key` in the first `hello` frame |
| Follow-ups | Send `conversation_id` (from `done` or the `x-conversation-id` header) | Same socket; send another `message` |
Both send the same objects, in this order: `status` (`searching`), one or more `results`, `status` (`answering`), many `delta`, then `done`. An `error` can replace any of them and ends the turn.
## Request (POST)
| Field | Type | What it does |
| --- | --- | --- |
| `text` | string, ≤2,000 chars, required | The visitor's message. Send only the new message; the server keeps the history. |
| `domain` | string | The company Dax answers about. Default: your own. |
| `conversation_id` | string | Continue a conversation: from `done`, or the `x-conversation-id` response header. |
| `options.length` | `short` `standard` `detailed` | Default: your setting in the Indax app. |
| `options.language` | e.g. `es`, `de`, `ja` | Default: the visitor's language. |
| `context` | object | See [Page context](/docs/products-api/page-context). |
| `instructions` | string, ≤500 chars | Server-only keys: a note for this turn, e.g. "returning customer". |
## What comes back
| Object | Fields | Meaning |
| --- | --- | --- |
| `status` | `state` | `searching` (Dax is looking things up), then `answering` (the text is about to stream). Optional to show. |
| `results` | `items[]`: `id`, `type`, `title`, `url`, `image`, `snippet` | Pages and products Dax found. Can arrive several times in one turn, each with new items only (no repeats): append them. Show as cards or links. |
| `delta` | `text` | The next piece of the answer. Append it, as plain text or Markdown with HTML off. |
| `done` | `conversation_id`, `credits_used`, `timing` | The turn is over. `timing` in ms: `first_frame_ms`, `first_results_ms`, `first_token_ms`, `total_ms`. |
| `error` | `code`, `message` | `message` is safe to show the visitor. |
## WebSocket
```js
const ws = new WebSocket("wss://api.indax.net/v1/chat");
ws.onopen = () => ws.send(JSON.stringify({ type: "hello", key: "indax_live_...", domain: "mpechicago.com" }));
ws.onmessage = (e) => {
const m = JSON.parse(e.data);
if (m.type === "ready") ws.send(JSON.stringify({ type: "message", text: "Which grinder fits activated carbon?" }));
if (m.type === "delta") answer.textContent += m.text;
if (m.type === "results") addCards(m.items); // may arrive more than once: append
if (m.type === "done") console.log("credits:", m.credits_used);
};
```
| You send | When |
| --- | --- |
| `hello` `{ key, domain?, conversation_id?, context? }` | First, within 10 s. Use a key that allows your website. |
| `message` `{ text, options?, context? }` | After `ready`, one at a time (wait for `done`). |
| `context` `{ context }` | The visitor moved to another page. |
| `abort` | Stop the current answer. |
`ready` returns `conversation_id` (store it in `sessionStorage` and send it in `hello` after a reload), plus the `greeting` and `suggested_questions` your admins set, for your chat window.
| Close code | Meaning |
| --- | --- |
| `4401` | Missing, invalid or revoked key. |
| `4403` | This website is not on the key's allowed websites. |
| `4402` | Credits used up. Show a contact link. |
| `4404` | `domain` is not on the Indax network. |
| `4400` | A frame was not valid JSON. |
Any other close: reconnect after 2 s with the same `conversation_id`.
## Steer Dax
Try it above: **Steer** opens length, language and `instructions`.
| Where | What you set | Applies to |
| --- | --- | --- |
| **Portal › Dax** in the Indax app | Tone, answer length, hand-off to sales (and the link), topics to avoid, extra instructions (up to 1,000 characters), greeting, suggested questions | Every chat about your own company, on your portal and through the API |
| `options` on a message | `length`, `language` | That message |
| `instructions` on a message | A note for this turn, up to 500 characters: who the visitor is, what to offer, how long to answer | That message. Server-only keys only: a website key's `instructions` are ignored, because anyone can read a key in page code. |
```json
{
"text": "Which grinder fits activated carbon?",
"instructions": "The visitor came from our trade-show page. Answer in two sentences and offer a free material test."
}
```
Indax's own rules always come first, then your Portal settings, then `instructions`, then the visitor's message. Steering changes how Dax answers, never what it may read or claim: it answers only from the company's catalog and website, links the page it used, and never invents a product, spec, price or certification, or promises stock or lead times.
---
# Page context
> Tell the API where the visitor is, for better ranking and answers.
A visitor on your pet food page who asks "which conveyor do you recommend?" wants the pet food answer. Send `context` with a search or a chat message and Indax uses it. Try it: set `context.current.url` in the [Search playground](/docs/products-api/search).
```json
{
"session_id": "v_8f2c1",
"current": { "url": "https://www.example.com/conveyors/pet-food/", "title": "Pet Food Conveying" },
"trail": [{ "url": "https://www.example.com/industries/pet-food/", "at": "2026-12-02T15:02:40Z" }],
"referrer": "https://www.google.com/"
}
```
| Field | What it is |
| --- | --- |
| `session_id` | Your id for the visit (≤100 chars). Chat limits count per session. No emails or names. |
| `current` | The page the visitor is on: `url`, optional `title`. |
| `trail` | Earlier pages, oldest first. The newest 20 are used. |
| `referrer`, `utm` | Where the visitor came from. Only the host is kept. |
All fields are optional. Indax keeps only URLs on the company's own domain, reads the visit's topics from those pages, and then:
- **Search** moves matching results up a little (`context_applied: true`). Send `"boost": false` to turn it off.
- **Chat** uses the visit as background, never as instructions.
## Collect it in the browser
```html
```
Then send `context: window.indaxContext()` with each search or chat message. `sessionStorage` clears when the tab closes; no cookies. If your visitors must opt in to analytics, send context only after they do.
---
# Keys and credits
> Create a key, keep it safe, and what each request costs.
## Create a key
In the [Indax app](https://app.indax.co/developers), open **API › Create key** and choose **Products**. Only company admins can create and revoke keys.
| Allowed websites | Key works from | Use it for |
| --- | --- | --- |
| Your sites, e.g. `https://www.example.com` | Those sites' pages, and servers | A search box or chat window in the browser |
| Empty | Servers only | Your back end, a proxy, a nightly job |
`https://example.com` and `https://www.example.com` are different sites: list each, plus staging. A key used from another site gets `403 forbidden_origin`; a server-only key used from a browser gets `403 server_only_key`.
## Send it
```http
Authorization: Bearer indax_live_...
```
`X-Api-Key` also works. On the WebSocket, send it in the `hello` frame, never in the URL.
## Keep it safe
- A website key is visible in page code. That is expected: allowed websites and rate limits protect it.
- Never put a server-only key in page code or a mobile app. Keep it in an environment variable.
- One key per place (site, staging, agency), so you can revoke one alone. Revoked keys stop within a minute.
## Credits
Requests use your Indax plan's credits.
| Request | Credits |
| --- | --- |
| Search | 1 |
| Chat turn | 1 or more by tokens; most turns are 1 or 2 |
| Errors on Indax's side, retries with the same `x-request-id` | 0 |
Every response says what it used (`credits_used`). **Usage** in the Indax app shows API search and chat per key. When credits run out, search returns `402 credits_exhausted` and chat closes with `4402`.
---
# Errors and limits
> Every error, the rate limits, and how to retry.
## Error format
Every HTTPS error is JSON with a code you can branch on and a message you can show:
```json
{ "error": "rate_limited", "message": "More than 120 searches a minute with this key. Wait a moment, then try again." }
```
| Status | `error` | Meaning | What to do |
| --- | --- | --- | --- |
| 400 | `invalid` | A field is missing or out of range. The message names it. | Fix the request. |
| 401 | `unauthorized` | No key, a wrong key, or a revoked key. | Check the key. |
| 402 | `credits_exhausted` | Your plan's credits for this period are used up. | Show a fallback; an admin adds credits. |
| 403 | `forbidden_origin` | The browser's site is not on the key's allowed websites. | Add the site to the key in the Indax app. |
| 403 | `server_only_key` | A server-only key was used from a browser. | Use a website key in the browser. |
| 404 | `unknown_company` | `domain` names a company that is not on the Indax network. | Check the domain. |
| 429 | `rate_limited` | Too many requests. `Retry-After` says how many seconds to wait. | Wait, then retry. |
| 429 | `budget` | Chat is paused for today for your company. | Retry tomorrow; search still works. |
| 502 | `search_failed`, `chat_failed` | Indax could not answer. Not charged. | Retry once after 1 second. |
| 503 | `unavailable` | The API is paused for maintenance. | Retry later. |
In chat, errors arrive as `error` objects with a `code`: `busy` (a message arrived before `done`), `rate_limited`, `budget` (chat paused for today), `invalid` (empty, too long, or 30 messages reached), `model_error` or `chat_failed` (try again). WebSocket close codes: see [Chat](/docs/products-api/chat#websocket).
## Limits
| Limit | Value |
| --- | --- |
| Searches per key | 120 a minute |
| Chat messages per visitor (`session_id`, else IP address) | 20 every 10 minutes |
| Open chat sockets per IP address | 20 |
| `q` | 200 characters |
| Chat message | 2,000 characters |
| Messages in one conversation | 30 visitor messages |
| Page context trail | 50 accepted, newest 20 used |
| Results per search page / per query | 50 / 100 |
| Idle chat socket | Closed after 15 minutes |
Need higher limits? Email [andre@indax.co](mailto:andre@indax.co).
## Retry
```js
async function withRetry(fn, tries = 3) {
for (let i = 0; ; i++) {
const res = await fn();
if (res.ok || i === tries - 1) return res;
if (res.status === 429) {
await new Promise((r) => setTimeout(r, Number(res.headers.get("retry-after") || 2) * 1000));
} else if (res.status >= 500) {
await new Promise((r) => setTimeout(r, 1000 * (i + 1)));
} else {
return res; // 4xx other than 429: retrying will not help
}
}
}
```
Send the same `x-request-id` on each try, so a retried search is charged once.
---
# For AI coding agents
> One page an AI coding agent can read to build a working integration.
This page is written for an AI coding agent (Claude Code, Cursor, Copilot and others). Give it this page, or the whole section as one file: `https://indax.co/docs/products-api/llms-full.txt`. Every docs page is also available as Markdown: add `.md` to its URL.
## Task brief
You are adding Indax search and chat to a company's website. Indax indexes the company's public website (products, parts, pages, PDFs) and runs Dax, an assistant scoped to that company. You build the user interface; the API does the rest.
- Base URL: `https://api.indax.net`
- Key: from the company's Indax app, the **API** page of the Indax app. Format `indax_live_` + 32 characters. Read it from configuration, never hard-code it in source control.
- Two key kinds: **website** keys (allowed websites listed; used in browser code) and **server-only** keys (no allowed websites; used only from servers).
## Endpoints
### Search
```
POST /v1/search
Authorization: Bearer
Content-Type: application/json
{"q": "", "domain": "", "limit": 10, "cursor": "", "types": ["products","parts","pages","documents"], "context": { ... }}
```
Response:
```json
{"id":"…","results":[{"id":"…","type":"product|part|page|document","title":"…","url":"https:///…","summary":"…","image":"…|null","part_number":"…|null","category":"…|null","page_kind":"…"}],"next_cursor":"10|null","total":23,"context_applied":false,"credits_used":1,"timing":{"search_ms":180,"total_ms":205}}
```
Rules: only `q` is required. `domain` picks the company (any company on the Indax network; unknown → `404 unknown_company`); each result has `company`. `filters: {category, brand, cert, specs}` and `facets: true` filter products. Link each result to `url`. Show `image` when present. Page with `cursor` = previous `next_cursor` until it is `null`.
### Chat (WebSocket)
```
wss://api.indax.net/v1/chat
→ {"type":"hello","key":"","domain":"","conversation_id":"","context":{...}}
← {"type":"ready","conversation_id":"…","resumed":false,"greeting":"…|null","suggested_questions":["…"]}
→ {"type":"message","text":"","context":{...}}
← {"type":"status","state":"searching"}
← {"type":"results","items":[{"id","type","title","url","image","snippet"}]} (0 or more; new items each time, append)
← {"type":"status","state":"answering"}
← {"type":"delta","text":"…"} (repeat; append in order)
← {"type":"done","conversation_id":"…","credits_used":1,"timing":{"first_frame_ms":120,"first_results_ms":300,"first_token_ms":2400,"total_ms":5100}}
← {"type":"error","code":"…","message":""}
→ {"type":"abort"} (stop the current answer)
→ {"type":"context","context":{...}} (visitor moved to another page)
```
Rules:
1. Send `hello` first, within 10 seconds. Send `message` only after `ready`.
2. One `message` at a time: wait for `done` or `error` before the next. A second message while answering returns `error` with `code: "busy"`.
3. The server keeps the conversation. Send only the new text. Store `conversation_id` in `sessionStorage` and send it in `hello` after a reconnect.
4. Close codes: `4401` bad or missing key → stop and show "chat unavailable"; `4403` site not allowed → stop; `4402` out of credits → stop and show a contact link; `4400` bad frame → fix the client. Any other close → reconnect after 2 seconds.
5. Render `delta` text as plain text, or as Markdown with HTML disabled. Never insert it as raw HTML.
### Chat (HTTP fallback)
`POST /v1/chat` with `Authorization` and `{"text": "...", "conversation_id": "..."}` returns `text/event-stream`: one `data: ` line per server frame above. Use it from a server or where WebSockets are blocked.
### Context (optional, both endpoints)
```json
{"session_id":"","current":{"url":"","title":""},"trail":[{"url":"…","title":"…","at":""}],"referrer":""}
```
Only URLs on the company's domain are used; the newest 20 trail pages count. It improves ranking and answers. Build it from `location.href`, `document.title` and a `sessionStorage` list of visited pages.
## Errors (HTTPS)
`{"error":"","message":""}` with status: `400 invalid`, `401 unauthorized`, `402 credits_exhausted`, `403 forbidden_origin | server_only_key`, `429 rate_limited | budget` (honor `Retry-After`), `502 search_failed | chat_failed` (retry once), `503 unavailable`.
## Limits
Searches: 120 a minute per key. Chat: 20 messages every 10 minutes per visitor (`session_id`, else IP). Message ≤ 2,000 characters; 30 visitor messages per conversation; 20 open sockets per IP.
## Credits
Search = 1 credit. Chat turn = max(1, ⌈(input − 0.9·cached + 5·output tokens) ÷ 20,000⌉), usually 1–2. Each response returns `credits_used`. Debounce search-as-you-type (250 ms, 2+ characters).
## Minimal working client (TypeScript, browser)
```ts
const KEY = import.meta.env.VITE_INDAX_KEY as string; // a website key that allows this site
const API = "https://api.indax.net";
export async function search(q: string, cursor?: string) {
const res = await fetch(`${API}/v1/search`, {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ q, limit: 10, cursor, context: { current: { url: location.href, title: document.title } } }),
});
const body = await res.json();
if (!res.ok) throw Object.assign(new Error(body.message), { code: body.error, status: res.status });
return body as { results: Array<{ id: string; type: string; title: string; url: string; summary: string; image: string | null }>; next_cursor: string | null };
}
export function chat(handlers: { onReady?: (greeting: string | null, suggestions: string[]) => void; onDelta: (t: string) => void; onResults?: (items: any[]) => void; onDone?: () => void; onError?: (msg: string) => void }) {
let ws: WebSocket; let ready = false; let busy = false;
const open = () => {
ws = new WebSocket(`${API.replace("https", "wss")}/v1/chat`);
ws.onopen = () => ws.send(JSON.stringify({ type: "hello", key: KEY, conversation_id: sessionStorage.getItem("indax_cid") ?? undefined }));
ws.onmessage = (e) => {
const m = JSON.parse(e.data);
if (m.type === "ready") { ready = true; sessionStorage.setItem("indax_cid", m.conversation_id); handlers.onReady?.(m.greeting, m.suggested_questions); }
else if (m.type === "delta") handlers.onDelta(m.text);
else if (m.type === "results") handlers.onResults?.(m.items);
else if (m.type === "done") { busy = false; handlers.onDone?.(); }
else if (m.type === "error") { busy = false; handlers.onError?.(m.message); }
};
ws.onclose = (e) => { ready = false; if (![4400, 4401, 4402, 4403].includes(e.code)) setTimeout(open, 2000); else handlers.onError?.("Chat is not available."); };
};
open();
return {
send(text: string) {
if (!ready || busy) return false;
busy = true;
ws.send(JSON.stringify({ type: "message", text, context: { current: { url: location.href, title: document.title } } }));
return true;
},
stop() { ws.send(JSON.stringify({ type: "abort" })); },
close() { ws.close(1000); },
};
}
```
## Common mistakes
- Putting the key in the WebSocket URL. Send it in `hello`.
- Using a server-only key in the browser (`403 server_only_key`), or a website key from a site not on its list (`403 forbidden_origin`).
- Sending the whole conversation each turn. Send only the new message; keep `conversation_id`.
- Sending a second `message` before `done`.
- Inserting `delta` text as HTML.
- Calling search on every keystroke without a debounce.
- Sending names or emails in `session_id` or context.
## Test checklist
- [ ] A search for a known product returns it first, with a link to the company's page.
- [ ] Paging with `next_cursor` returns no duplicates.
- [ ] The chat streams `delta` frames, then `done`; a follow-up question keeps the context.
- [ ] Reloading the page resumes the conversation (`ready.resumed: true`).
- [ ] An invalid key shows a friendly message (close `4401` / `401`).
- [ ] `429` waits for `Retry-After`; `402` shows a contact link.
- [ ] The key is read from configuration and is not in the repository.
---
# OpenAPI spec
```yaml
openapi: 3.1.0
info:
title: Indax Search & Chat API
version: "1.0.0"
summary: Your catalog, pages and Dax on your own website.
description: |
Search your products, parts, pages and PDFs, and chat with Dax, the Indax assistant, scoped to
your company. Create a key in the Indax app under API › Keys. Every request uses credits
from your Indax plan: a search is 1 credit; a chat turn is counted by tokens.
Chat streams over a WebSocket at wss://api.indax.net/v1/chat (see the docs); the same events
are available over Server-Sent Events from POST /v1/chat.
contact:
name: Indax
url: https://indax.co/docs/products-api
servers:
- url: https://api.indax.net
security:
- bearerKey: []
paths:
/v1/search:
post:
operationId: search
summary: Search your products, parts, pages and PDFs
parameters:
- $ref: "#/components/parameters/RequestId"
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/SearchRequest" }
examples:
simple: { value: { q: "grinder for phenolic resin" } }
withContext:
value:
q: "conveyor"
limit: 5
context:
session_id: "v_8f2c1"
current: { url: "https://www.example.com/applications/pet-food/" }
responses:
"200":
description: Results, best first.
content:
application/json:
schema: { $ref: "#/components/schemas/SearchResponse" }
"400": { $ref: "#/components/responses/Error" }
"401": { $ref: "#/components/responses/Error" }
"402": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
"429": { $ref: "#/components/responses/Error" }
"502": { $ref: "#/components/responses/Error" }
/v1/chat:
post:
operationId: chat
summary: One chat turn, streamed as Server-Sent Events
description: |
Each event is a line `data: {json}` with one of the ChatEvent objects. The WebSocket at
wss://api.indax.net/v1/chat sends the same objects as frames. The server keeps the
conversation: send only the new message and the conversation_id from the last done event.
parameters:
- $ref: "#/components/parameters/RequestId"
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/ChatRequest" }
examples:
first: { value: { text: "Which conveyor is best for almonds?" } }
followUp: { value: { text: "And for 2,000 cubic feet per hour?", conversation_id: "a1b2c3d4e5f6a7b8" } }
responses:
"200":
description: A stream of ChatEvent objects.
headers:
x-conversation-id: { schema: { type: string } }
content:
text/event-stream:
schema: { $ref: "#/components/schemas/ChatEvent" }
"400": { $ref: "#/components/responses/Error" }
"401": { $ref: "#/components/responses/Error" }
"402": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"429": { $ref: "#/components/responses/Error" }
/v1/session:
post:
operationId: session
summary: Check a key and open or resume a conversation (no credits)
requestBody:
content:
application/json:
schema:
type: object
properties:
conversation_id: { type: string, pattern: "^[A-Za-z0-9_-]{8,64}$" }
domain: { type: string }
responses:
"200":
description: The conversation to use.
content:
application/json:
schema:
type: object
required: [conversation_id, resumed]
properties:
conversation_id: { type: string }
resumed: { type: boolean, description: "true when the given conversation exists for this key" }
company: { type: string, description: "The key's company domain" }
greeting: { type: [string, "null"], description: "The greeting set in the Indax app" }
suggested_questions: { type: array, items: { type: string }, description: "Up to 4, set in the Indax app" }
"401": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
components:
securitySchemes:
bearerKey:
type: http
scheme: bearer
description: "Your key: Authorization: Bearer indax_live_..."
parameters:
RequestId:
name: x-request-id
in: header
required: false
description: Your id for this request (8-100 characters). A retry with the same id is never charged twice.
schema: { type: string }
responses:
Error:
description: An error with a code and a message you can show.
content:
application/json:
schema: { $ref: "#/components/schemas/Error" }
schemas:
Error:
type: object
required: [error, message]
properties:
error:
type: string
enum: [invalid, unauthorized, server_only_key, forbidden_origin, unknown_company, rate_limited, budget, credits_exhausted, unavailable, search_failed, chat_failed]
message: { type: string }
PageRef:
type: object
required: [url]
properties:
url: { type: string, description: "A page on your own website. Other sites are ignored." }
title: { type: string, maxLength: 300 }
at: { type: string, description: "ISO time the visitor opened it" }
Context:
type: object
description: Where the visitor is on your website. Optional; it makes answers and ranking fit the visit.
properties:
session_id: { type: string, maxLength: 100, description: "Your visitor or session id (limits and analytics)" }
current: { $ref: "#/components/schemas/PageRef" }
trail:
type: array
maxItems: 50
description: Pages before, oldest first. The newest 20 are used.
items: { $ref: "#/components/schemas/PageRef" }
referrer: { type: string }
utm:
type: object
properties:
source: { type: string }
medium: { type: string }
campaign: { type: string }
SearchRequest:
type: object
required: [q]
properties:
q: { type: string, minLength: 1, maxLength: 200 }
domain:
description: The company (or up to 20 companies) to show results from, by website domain. Any company on the Indax network. Default your own company.
oneOf: [{ type: string }, { type: array, items: { type: string }, maxItems: 20 }]
types:
type: array
items: { type: string, enum: [products, parts, certificates, pages, documents] }
description: Default all five.
limit: { type: integer, minimum: 1, maximum: 50, default: 10 }
cursor: { type: string, description: "next_cursor from the previous page" }
context: { $ref: "#/components/schemas/Context" }
boost: { type: boolean, default: true, description: "Rank results that match the visit a little higher" }
filters:
type: object
description: Product filters (products and parts only). Use the values facets returns.
properties:
category: { type: string, description: "A facets.category label" }
brand: { type: string, description: "A facets.brand value" }
cert: { type: string, description: "A facets.cert label, e.g. CE, UL, NSF" }
specs: { type: object, additionalProperties: { type: string }, description: "{facets.specs[].key: one of its values[].label}" }
facets: { type: boolean, default: false, description: "Also return the filter values the results offer, with counts" }
SearchResult:
type: object
required: [id, type, title, url]
properties:
id: { type: string }
type: { type: string, enum: [product, part, certificate, page, document] }
company: { type: string, description: "The company domain the result belongs to" }
title: { type: string }
url: { type: string, description: "The company's own page for the result" }
summary: { type: string }
image: { type: [string, "null"] }
part_number: { type: [string, "null"] }
category: { type: [string, "null"] }
page_kind: { type: string, description: "Pages: blog, application, docs, category, product, contact, other" }
brand: { type: [string, "null"], description: "Products and parts: the maker" }
certs: { type: array, items: { type: string } }
specs: { type: array, items: { type: object, properties: { name: { type: string }, value: { type: string } } } }
SearchResponse:
type: object
required: [id, results, next_cursor, credits_used]
properties:
id: { type: string, description: "The request id" }
results: { type: array, items: { $ref: "#/components/schemas/SearchResult" } }
next_cursor: { type: [string, "null"] }
total: { type: integer }
context_applied: { type: boolean }
facets:
type: object
description: With facets=true.
properties:
category: { type: array, items: { $ref: "#/components/schemas/FacetValue" } }
brand: { type: array, items: { $ref: "#/components/schemas/FacetValue" } }
cert: { type: array, items: { $ref: "#/components/schemas/FacetValue" } }
specs:
type: array
items:
type: object
properties:
key: { type: string }
label: { type: string }
values: { type: array, items: { type: object, properties: { label: { type: string }, n: { type: integer } } } }
credits_used: { type: integer }
timing:
type: object
properties:
search_ms: { type: integer }
total_ms: { type: integer }
FacetValue:
type: object
properties:
value: { type: string }
label: { type: string }
n: { type: integer }
ChatRequest:
type: object
required: [text]
properties:
text: { type: string, minLength: 1, maxLength: 2000 }
domain: { type: string, description: "The company Dax answers about, by domain. Default your own company." }
conversation_id: { type: string, pattern: "^[A-Za-z0-9_-]{8,64}$" }
context: { $ref: "#/components/schemas/Context" }
options:
type: object
properties:
length: { type: string, enum: [short, standard, detailed] }
language: { type: string, description: "e.g. es, de, ja. Default: the visitor's language" }
instructions:
type: string
maxLength: 500
description: Server-only keys. A short note for this request; it never overrides your Portal settings or Indax's rules.
ResultItem:
type: object
properties:
id: { type: string }
type: { type: string, enum: [product, part, page, document] }
title: { type: string }
url: { type: string }
image: { type: [string, "null"] }
snippet: { type: string }
ChatEvent:
oneOf:
- type: object
title: status
required: [type, state]
properties: { type: { const: status }, state: { type: string, enum: [searching, answering] } }
- type: object
title: delta
required: [type, text]
properties: { type: { const: delta }, text: { type: string } }
- type: object
title: results
required: [type, items]
description: Additive. The first arrives before the answer (from the visitor's message); later ones add what Dax looked up. A URL never repeats.
properties: { type: { const: results }, items: { type: array, items: { $ref: "#/components/schemas/ResultItem" } } }
- type: object
title: done
required: [type, conversation_id, credits_used]
properties:
type: { const: done }
conversation_id: { type: string }
credits_used: { type: integer }
timing:
type: object
properties:
first_frame_ms: { type: [integer, "null"] }
first_results_ms: { type: [integer, "null"] }
first_token_ms: { type: [integer, "null"] }
total_ms: { type: integer }
- type: object
title: error
required: [type, code, message]
properties: { type: { const: error }, code: { type: string }, message: { type: string } }
```