# Search as you type API overview

> Authentication, request, response, errors and limits of POST /api/v0/searchAsYouType, plus the browser SDK functions for rendering results yourself.

The search as you type API returns ranked, personalized product matches and filter options for what a shopper is typing, using the settings under **Personalization › Search As You Type**. It has one endpoint under `https://releva.ai/api/v0`:

| Endpoint                              | Purpose                                       |
| ------------------------------------- | --------------------------------------------- |
| `POST /searchAsYouType/{accessToken}` | Products, filters and match count for a query |

**When to use it.** Your storefront renders its own search results (a custom theme, a headless front end, a platform connector). If you use the Releva JavaScript snippet with the default dropdown you do not call it: the snippet does, on every keystroke. For what the endpoint does with the settings, read [How search as you type works](https://releva.ai/documentation/learn/search-as-you-type/how-search-as-you-type-works/).

Note the path: `searchAsYouType`, not `search-as-you-type`. `POST /api/v0/search` is a different endpoint that only tracks a search; see the [Events API overview](https://releva.ai/documentation/reference/events/send-search-events/).

## Authentication

Use the shop’s **access token**, the public token the browser snippet uses, not the secret key. Find it under **Settings › Shop & Integration**; see [Find your API keys](https://releva.ai/documentation/guides/shop-settings/find-your-api-keys/). Send it as the last path segment:

```plaintext
POST https://releva.ai/api/v0/searchAsYouType/$RELEVA_ACCESS_TOKEN
```

You can also send `authorization: Bearer $RELEVA_ACCESS_TOKEN`. The header wins over the path, but the path segment must still be present: `POST /api/v0/searchAsYouType/` without a segment answers `404` with an HTML page.

Authentication failures answer **`400`**, not `401`:

| Problem                        | Message                                                                       |
| ------------------------------ | ----------------------------------------------------------------------------- |
| Token is not a UUID            | `The access token you provided is invalid.`                                   |
| No shop has this token         | `Domain with the provided access token cannot be found.`                      |
| Header is not `Bearer <token>` | ``Authorization header is malformed. It should look like `Bearer <string>`.`` |

A shop that has been switched off answers **`402`** with `Domain is disabled. Please reach out to support@releva.ai to enable it.`; a shop whose plan limit is exceeded answers `402` with `Value delivery is paused for this domain because usage exceeded the plan limit. Please raise your limit or reach out to support@releva.ai to resume.`.

## Request

Send JSON with `content-type: application/json`. The browser snippet sends the same body as `application/x-www-form-urlencoded` with one field, `formPayload`, holding the base64 of the URI-encoded JSON; you can do the same. Any other content type leaves the body empty and answers `400 {"message":"The 'context' field is required. The 'search' field is required."}`.

The top level is strict: an unknown key such as `limit` answers `400 {"message":"The object '' contains forbidden keys: 'limit'."}`.

| Field                                                  | Type   | Required | Notes                                                                                                                                               |
| ------------------------------------------------------ | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `search`                                               | string | yes      | What the shopper typed. An empty string matches every available product.                                                                            |
| `filterBy`                                             | array  | no       | Selected filter values. Each item needs all of `key`, `type` and `value`.                                                                           |
| `filterBy[].key`                                       | string | yes      | `Categories` for the category filter, otherwise the product custom-field key (for example `brand`).                                                 |
| `filterBy[].type`                                      | string | yes      | Custom-field type: `string`, `numeric` or `date`. Required even for `Categories`, where it is ignored.                                              |
| `filterBy[].value`                                     | string | yes      | A `filters[].options[].value` from an earlier response. For categories the full path, such as `Men/Shirts`.                                         |
| `context`                                              | object | yes      | Who is searching and where. Other keys are accepted.                                                                                                |
| `context.profile.id`                                   | string | no       | Releva profile id from the `push` response. Needed for personalized ranking and for the **Interactions** statistic.                                 |
| `context.deviceId`                                     | string | no       | Browser device id (the snippet’s `rlv_p` cookie). Used when `profile.id` is absent.                                                                 |
| `context.profile.email`, `context.profile.phoneNumber` | string | no       | Legacy identification. The profile is looked up **or created**. Prefer `profile.id`.                                                                |
| `context.page.locale`                                  | string | no       | Language of the catalog to search (`en`). **Defaults to the shop’s locale**; a catalog in another language then returns `total: 0`. Always send it. |
| `context.page.market`                                  | string | no       | Shopify market handle. Products of that market and products without a market match.                                                                 |
| `context.page.url`                                     | string | no       | Stored on the interaction event.                                                                                                                    |
| `context.mode`                                         | string | no       | `debug`, `layout-edit` or `search-edit` return results even when the feature is switched off.                                                       |
| `context.group`                                        | string | no       | A/B test group as sent by the snippet.                                                                                                              |

```plaintext
curl -X POST "https://releva.ai/api/v0/searchAsYouType/$RELEVA_ACCESS_TOKEN" \
  -H 'content-type: application/json' \
  -d '{
    "search": "shirt",
    "filterBy": [{ "key": "Categories", "type": "string", "value": "Men/Shirts" }],
    "context": {
      "page": { "locale": "en", "url": "https://demo-store.example.com/search" },
      "profile": { "id": "demo-device-sayt-1" }
    }
  }'
```

## Response

`200` with `products`, `filters`, `total` and `query`:

```plaintext
{
  "products": [
    {
      "id": "DEMO-1001",
      "name": "Linen Summer Shirt",
      "locale": "en",
      "currency": "EUR",
      "listPrice": 39.9,
      "price": 39.9,
      "discountPercent": 0,
      "sku": "DEMO-1001-M",
      "categories": ["Men/Shirts", "Summer"],
      "url": "https://demo-store.example.com/products/linen-summer-shirt?rlv_aid=1&rlv_apid=DEMO-1001&rlv_apos=0",
      "imageUrl": "https://demo-store.example.com/images/linen-summer-shirt.jpg",
      "custom": {
        "string": [
          { "key": "brand", "values": ["Demo Basics"] },
          { "key": "color", "values": ["white", "sand"] }
        ],
        "numeric": [],
        "date": []
      },
      "variants": [{ "variantId": "DEMO-1001", "optionValues": [], "available": true }]
    }
  ],
  "filters": [
    {
      "key": "Categories",
      "type": "string",
      "title": "Category",
      "options": [
        { "value": "Men/Shirts", "label": "Shirts", "selected": false },
        { "value": "Summer", "label": "Summer", "selected": false }
      ]
    },
    {
      "key": "brand",
      "type": "string",
      "title": "Brand",
      "options": [{ "value": "Demo Basics", "label": "Demo Basics", "selected": false }]
    }
  ],
  "total": 1,
  "query": "shirt"
}
```

| Field                        | Notes                                                                                                                                                                                                                                                                                                                |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `products[]`                 | At most **Number of Products to Show** (admin setting, default 6). `price` is the current price after discount.                                                                                                                                                                                                      |
| `products[].url`             | The product URL with `rlv_aid=1`, `rlv_apid=<product id>`, `rlv_apos=<position>` and, when a product feed ranked it, `rlv_pfid=<feed id>`. **Keep these parameters** in your links: the snippet reads them on the product page and records the click, which attributes later cart additions and purchases to search. |
| `products[].matchedVariant`  | Present when a word of the query names a colour one of the variants has.                                                                                                                                                                                                                                             |
| `products[].selectedVariant` | Present when the selected filters identify one variant; use it to deep-link (`{{url}}&variant={{selectedVariant.variantId}}`).                                                                                                                                                                                       |
| `filters[]`                  | The filters configured in the admin that have at least one option for this query. `title` is the text to show. Up to 5 options each, by frequency among the top 100 matches; `selected` is `true` for the values you sent in `filterBy`. For categories `value` is the full path and `label` the last segment.       |
| `total`                      | Number of matches, not capped by the number returned.                                                                                                                                                                                                                                                                |
| `query`                      | The `search` value as sent, for a “View all results” link.                                                                                                                                                                                                                                                           |

When `profile.id` or `deviceId` is sent, one `autocompleteInteraction` event is recorded for the returned products; it is what the **Interactions** tile counts. Without either, results are served and nothing is recorded.

## Errors

Errors have one shape, `{"message": "..."}`. Several validation messages are joined with a space.

| Status | Message                                           | When                                                                                                                                                             |
| ------ | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | `The 'search' field is required.`                 | `search` missing                                                                                                                                                 |
| `400`  | `The 'context' field is required.`                | `context` missing                                                                                                                                                |
| `400`  | `The 'search' field must be a string.`            | `search` is not a string                                                                                                                                         |
| `400`  | `The 'filterBy[0].type' field is required.`       | a `filterBy` item lacks `type` (same for `key` and `value`)                                                                                                      |
| `400`  | `The object '' contains forbidden keys: 'limit'.` | unknown top-level key                                                                                                                                            |
| `400`  | `formPayload is missing from request body`        | form-encoded body without `formPayload`                                                                                                                          |
| `400`  | `Search As You Type functionality is disabled!`   | the switch is off and `context.mode` is not a preview mode                                                                                                       |
| `400`  | see Authentication                                | bad or unknown token                                                                                                                                             |
| `402`  | see Authentication                                | shop disabled or plan limit exceeded                                                                                                                             |
| `404`  | HTML `Cannot POST /api/v0/searchAsYouType/`       | no token segment in the path                                                                                                                                     |
| `413`  | `request entity too large`                        | body over 800 KB (limit from server code, not reproduced)                                                                                                        |
| `500`  | `An internal error occurred.`                     | unexpected error. Also returned when the shop has **never** opened the Search As You Type page: create the settings with **Set up without turning it on** first. |

## Limits

* Body size: 800 KB for JSON, 2 MB for the form-encoded variant.
* Rate limits: none on this endpoint. The snippet waits 200 ms after the last keystroke; do the same.
* Up to 100 matches are ranked; at most **Number of Products to Show** are returned; 5 options per filter.
* `context.page.locale`, `context.deviceId` and the keys inside `context` are not validated: a wrong locale such as `en-US` is accepted and returns `total: 0`.

## Browser SDK

With the snippet installed and the default **Releva dropdown** render mode there is nothing to call. When the `push` response contains `search`, the snippet attaches to every element matching the CSS selector and renders the configured layout.

To use Releva’s results in your own UI, the `Releva` global exports:

```plaintext
// Results only; returns a Promise of the endpoint's 200 body.
const { products, filters, total, query } = await Releva.searchAsYouType({
  search: 'shirt',
  filterBy: [{ key: 'brand', type: 'string', value: 'Demo Basics' }], // optional
});


// Your own container, Releva's Search layout:
const html = Releva.renderSearchTemplate({ products, filters, total, query });
Releva.mountSearchPanel('#my-search-results', html);
```

* `Releva.searchAsYouType(data)` posts to the endpoint with the page, profile id and device id the snippet already knows.
* `Releva.renderSearchTemplate(data)` renders the **Search** layout chosen in the admin and throws if none was configured or the snippet has not received the search settings yet.
* `Releva.mountSearchPanel(selector, html)` puts the markup into an element of your page; clicks on filter values inside it (elements with `data-value` inside a parent with `data-key` and `data-type`) re-run the last query with that filter.
* `Releva.enableSearchAsYouType(searchConfig, context?)` attaches the dropdown manually, for integrations that get the search settings outside the normal `push` flow.

Preview modes on the shop URL: `?rlv_mode=debug` shows the panel even when the feature is off or the visitor is in the control group; `?rlv_mode=search-edit` is used by the admin layout editor.

## Versioning

The endpoint is under `/api/v0`. Changes are listed in the [API changelog](https://releva.ai/documentation/changelog/api/). The top level of the request is strict, so new request fields are safe to send only after they appear here.

## Next steps

* [How search as you type works](https://releva.ai/documentation/learn/search-as-you-type/how-search-as-you-type-works/): Learn how products are picked and ranked and how clicks are attributed.
* [Set up search as you type](https://releva.ai/documentation/guides/search-as-you-type/set-up-search-as-you-type/): Connect your search box, choose a layout and switch the feature on.
* [Events API overview](https://releva.ai/documentation/reference/events/overview/): Track searches, page views and purchases.
* [Catalog API overview](https://releva.ai/documentation/reference/catalog/overview/): Send the products the search reads.