> ## Documentation Index
> Fetch the complete documentation index at: https://docs.depict.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Upgrade from the Shopify search app API to V4

> Move a custom search integration from the Shopify search app API to V4. Routes, request and response fields, tracking, and worked JavaScript examples.

This page is for a storefront or native app that calls `/search_v2`, `/autocomplete_v2`, and `/events` on `runway.depict.ai`. It maps those calls to the Platform API's `/v4` endpoints.

For an integration that calls the v2 or v3 endpoints on `api.depict.ai`, use [Upgrade from v3/v2](https://docs.depict.ai/api-v4/upgrade.md). For a new integration, start at the [introduction](https://docs.depict.ai/api-v4/introduction.md).

## What changes

* The host becomes `https://api.depict.ai`. Every path starts with `/v4/{merchant}`.
* Read your store's markets and locales from [`context`](https://docs.depict.ai/api-v4/endpoints#context).
* Search uses [`browse`](https://docs.depict.ai/api-v4/endpoints#browse), which returns one JSON object. Remove the parser for `key:value` stream lines.
* Pass the response's `cursor` to get the next page. There is no `page` parameter.
* Set `limit` explicitly. The default changes from 30 products to 24.
* Convert filter objects to a `filter_by` string.
* Suggestions are typed objects, not strings with completion markup.
* Events use NDJSON. Each card's `tracking_id` replaces separate search and position fields on impressions and clicks.

The mappings below describe fields, not identical results. Check ranking, suggestions, product grouping, filters, and tracking before you move shopper traffic.

## Routes

| Shopify search app route | Use instead |
| - | - |
| `POST /search_v2` | [`browse`](https://docs.depict.ai/api-v4/endpoints#browse) with `query` |
| `GET /autocomplete_v2` | [`suggest`](https://docs.depict.ai/api-v4/endpoints#suggest) with `query` |
| `POST /events` | [`POST /v4/{merchant}/events`](https://docs.depict.ai/api-v4/events) for the supported event types |
| The store's countries and languages | [`context`](https://docs.depict.ai/api-v4/endpoints#context) |
| `GET /empty-state-products`, if your client uses it | Separate `suggest` and `browse` requests. See [Start view](#start-view) |

Every data endpoint takes GET parameters or a POST JSON body. Events take only POST. V4 does not need an API key or `depict_token`.

## Requests

Read `GET /v4/{merchant}/context` first. Use your store's name in Depict as `{merchant}`. Confirm it instead of assuming that every old `merchant_id` is a V4 name.

| Old field | V4 field or action |
| - | - |
| `merchant_id` | The path's `{merchant}` |
| `query` | `query`, at most 512 characters |
| `country` | `market`: a market `key` from `context`, or a supported ISO country code |
| `locale` | `locale`, from that market's `locales`. If omitted, V4 uses its `default_locale` |
| `page` | `cursor` from the previous response |
| `limit` | `limit`, 1 to 100. Send `30` to keep the old default page size |
| `filters[].field`, `operator`, `value` | `filter_by`. See [Filters](#filters) |
| `sort: {field, order}` | A POST `sort` object, or `sort=<field>.<order>` in a GET |
| Search `session_id`, `device_id`, `search_id` | Omit. Shopper identity belongs in events. V4 returns a `request_id` |
| `entry_point`, `history`, `previous_search_id_in_conversation`, `while_typing`, `debug` | Omit. These are not V4 browse fields |
| `depict_token`, `X-Depict-Token` | Omit |

Each context market lists its `key`, `currency`, `locales`, and `default_locale`. Its optional `countries` list maps country codes to currencies. Select the shopper's market and language from these values. A market's presence does not mean every language is available there.

An unknown merchant, market, or locale produces an error. Unknown request fields also produce an error. Do not copy the old request body unchanged. See [Errors](https://docs.depict.ai/api-v4/contract.md#errors).

### Filters

Convert each old filter object to a clause. Join clauses with `&&`.

| Old `operator` | `filter_by` clause |
| - | - |
| `=` | `field:=value` |
| `!=` | `field:!=value` |
| `in` | `field:=[a,b]` |
| `not_in` | `field:!=[a,b]` |
| `>`, `>=`, `<`, `<=` | `field:>100`, `field:>=100`, `field:<100`, `field:<=100` |

For example, `{field: "price", operator: "<=", value: 500}` becomes `price:<=500`.

Use the `field` and value names returned in V4 `facets`. Do not assume old names such as `colors` are valid for every store. [`schema`](https://docs.depict.ai/api-v4/types#store-schema) lists the store's filter and sort fields.

Send booleans as `true` or `false`. Put values with spaces or punctuation in backticks, such as ``material:=`Organic cotton` ``. Use `URLSearchParams` to encode the whole expression in a GET. [Filters and sorts](https://docs.depict.ai/api-v4/filters.md) gives the full syntax.

### Sorts

| Old sort | V4 sort |
| - | - |
| `_relevance`, `desc` | `relevance`, or omit `sort` |
| `price`, `asc` or `desc` | `price`, with the same order |
| `created`, `desc` | `newest`, `desc` |

Read the available sorts from the response's `sorts` section. An unknown sort field produces an error.

### Sections

Without `include`, browse returns product cards, facets, and sorts. Request `include=facets,sorts,content` to add content pages.

In a GET, keep commas between `include` values unescaped. Encode each value separately.

Named sections replace the default sections. Thus, `include=content` does not also request facets and sorts. The card extras `attributes` and `variants` add card fields without removing the default sections. See [Sections](https://docs.depict.ai/api-v4/endpoints.md#sections).

## Responses

### Search pages

Use `response.json()` once. Do not split the response into stream lines.

| Old stream key or field | V4 field or action |
| - | - |
| `keyword` | `products` |
| `keyword_page_info.n_hits` | `total`. It can be absent; do not treat an absent total as zero |
| `keyword_page_info.has_next_page` | Whether `cursor` is present |
| `keyword_page_info.page`, `has_prev_page` | Keep loaded pages or cursor history in your client |
| `keyword_page_info.n_hits_approximate` | No equivalent flag. Show `total` only when present |
| `keyword_page_info.is_fallback` | No exact equivalent. See [Search matches](#search-matches) |
| `filter_facets`, `facet_counts`, `facet_counts_selected` | Structured `facets`, with values, counts, and selection state |
| `facet_price_stats` | A range facet's `min` and `max` |
| `facet_counts_contract` | No equivalent marker |
| `sorts` | `sorts`, with the active sort marked `selected` |
| `content_pages[].title`, `.url` | `content[].title`, `.url`, with `include=content` |
| `content_meta` | No equivalent object. `content_total` is available with `content_limit` |
| An `error` stream line | An HTTP error status and an `error` object |

Content entries can also have `description`, `snippet`, and `highlights`. Set `content_limit` to keep the same top content results on each product page. It also adds `content_total`. See [Browse](https://docs.depict.ai/api-v4/endpoints.md#browse).

### Pages

Pass the response's `cursor` in the next request. Keep the query, market, locale, filters, sort, sections, and limit unchanged. The last page has no cursor.

Reset the cursor when the shopper changes the search or a filter. Do not construct cursors or convert page numbers to cursors. Keep previous pages or cursors if your interface needs a back button.

### Search matches

On a search, `keyword_matched` says whether products matched the query's words. When it is `false`, V4 can return products closest in meaning.

This field is not a direct rename of `is_fallback`. Do not use the old flag's parser or assume that a search without keyword matches returns no products. See [Browse response](https://docs.depict.ai/api-v4/endpoints.md#response).

### Product cards

| Old product field | V4 field or action |
| - | - |
| `id`, `grouping_id` | `group_id` identifies the card's product or shown colorway. Do not assume identical ID values |
| `variant_id` | `variants[].product_id`; `selected` identifies the initial variant |
| `title` | Card `title` |
| `variant_title` | Variant `title` when it differs; `size` identifies the size |
| `handle` | `slug`. See [Product links](#product-links) |
| `image_urls` | `images` |
| `price` | `price.amount` |
| `original_price` | Optional `price.compare_at`, present when higher than `amount` |
| Product `currency` | Response `currency` |
| `out_of_stock` | Inverse of `in_stock`, subject to V4's grouping rule |
| `on_sale` | `badges` containing `sale` |
| `colors` | Optional `color` and `colorways`, or configured attributes. Not the old array contract |
| `tags`, `product_type`, and other custom fields | Configured `attributes`, with `include=attributes` |
| `search_id`, result position, or product ID used for click attribution | The card's `tracking_id`, unchanged |

IDs are strings. Do not parse a V4 ID as a number, remove a prefix, or substitute `group_id` for a variant ID. Use the store's required cart ID when its cart needs an ID other than `variants[].product_id`. See [Merchant attributes](https://docs.depict.ai/api-v4/attributes.md).

Use `variants[selected]` for the initial variant. If your cart needs another ID, read its declared attribute from that variant's `attributes`. The store's [`schema`](https://docs.depict.ai/api-v4/types#store-schema) identifies this attribute with `role: "add_to_cart"` and its configured `key`. Have Depict configure that required attribute if it is missing. Do not derive a cart ID by removing part of a V4 ID.

Use a variant's `title` when present; otherwise use the card's `title`. Use `size` for the size option.

Prices use major currency units: `1999` means 1,999 SEK. Convert to minor units only where your own renderer requires them. Use the response currency for every card. `currency` can be absent when there are no products.

Card `in_stock` describes whether any variant in any colorway is in stock in the selected market. Use a variant's `in_stock` for that size. The old stock flag and the new card flag can describe different groups.

#### Product links

Resolve `slug` using your storefront's product routes and locale root. Do not always append `/products/` to a value that is already a path.

For a Shopify storefront that returns a bare handle, build the product URL from its locale root, `/products/`, and that handle. For example, handle `rain-jacket` and root `/en-se/` give `/en-se/products/rain-jacket`. If `slug` is empty, the product has no path in that locale. See [Product](https://docs.depict.ai/api-v4/contract.md#product).

#### Attributes and tags

V4 does not automatically return every field from the old product object. Display settings determine which fields `include=attributes` adds.

Read variant values from `variants[i].attributes`. A card's `attributes` can combine distinct variant values into a list. Do not assume every card attribute is a scalar.

`tags` and `product_type` are built-in display attributes when configured. Other fields, such as `material`, `gender`, or `occasions`, need a configured source. Check required fields before switching. For filters, use returned facet values and counts instead of counts built only from loaded cards. See [Display attributes](https://docs.depict.ai/api-v4/attributes.md#display-attributes).

To receive `tags`, include it in the store's display settings and request `include=attributes`. Read the selected variant's `attributes.tags` when you need its tags. An absent attribute does not prove that the product has no tags. A configured `tags` list can be empty. Have Depict configure missing required fields, then verify their values on representative products.

#### Color filters

Replace filters derived from the old `colors` array with the returned facet's `field` and values. Do not derive filter values from words in shade labels. If your interface groups shades into color families, keep the original facet values for each group. Send those values in `filter_by`.

When present, `color.name` is the general color used by the color filter; `color.label` is the shopper-facing shade name. Use `colorways` to render color choices on a card. These fields do not guarantee the old array or its grouping rules. See [Color](https://docs.depict.ai/api-v4/contract.md#color).

The old product's `facet_values` has no fixed card-field replacement. Use response `facets` for filter controls, or configured attributes when you need product-level values.

## Suggestions

`GET /v4/{merchant}/suggest` replaces `/autocomplete_v2`. Map `merchant_id`, `country`, `locale`, and `query` as described above.

The old response contains completion strings with `**` markup. V4 returns typed objects:

```json theme={null}
{
  "request_id": "...",
  "suggestions": [
    {"type": "query", "query": "rain jacket"},
    {
      "type": "listing",
      "listing": {"id": "...", "title": "Jackets", "slug": "jackets", "type": "category", "images": []},
      "path": ["Women"]
    }
  ]
}
```

Render a query suggestion's `query` as text. Search for that value when selected. A listing suggestion opens its listing; it is not a query completion.

V4 returns matching listings followed by popular query suggestions. Its `limit` controls listing suggestions, not the number of query suggestions. There is no `**` completion markup or promise of identical suggestion text. See [Suggest](https://docs.depict.ai/api-v4/endpoints.md#suggest).

### Start view

Send an empty `query=` to `suggest` for start-view phrases and listing suggestions. Send `browse` without a query or listing for start-view products. Saved start-view pins apply to this browse request.

These are separate responses. Do not expect the old combined `/empty-state-products` response or its `localized_strings`. Keep your interface text in your client.

## Tracking

Send supported actions to `POST /v4/{merchant}/events`. Send one JSON event per line with `Content-Type: application/x-ndjson`. A JSON array is not the V4 event format.

Replace any old search-reporting proxy call with this endpoint. Omit `depict_token` and `X-Depict-Token`; V4 does not use them. The old proxy's request body is not the V4 event contract. Supply the required event fields in your client, including fields the proxy previously supplied.

### Event types

| Old `event_type` | V4 `type` |
| - | - |
| `product_impression` | `impression` |
| `product_click` | `click` |
| `add_to_cart` | `add_to_cart` |
| `page_view` of a product page | `product_view` |
| `purchase` | `purchase`, with an order in `purchase` |
| `autocomplete_accept` | No V4 event. Reports do not need it |

A product view is not a replacement for visits to other page types. See [Not available yet](#not-available-yet).

### Event fields

| Old field | V4 field or action |
| - | - |
| `merchant_id` | The path's `{merchant}` |
| `event_type` | `type` |
| `event_id` | Required `event_id`, generated by the client |
| `client_timestamp` | Required `ts`, as an ISO timestamp with an offset |
| `country` | Required `market`, as on the content request |
| `locale` | Optional `locale` |
| Persistent `device_id` | Required `session_id`, stable across visits |
| Visit-specific `session_id` | Do not use it as V4's persistent device ID |
| `search_id`, `position` | Omit. The card's `tracking_id` supplies response and position identity |
| Click or impression `product_id` | Use `tracking_id`; it identifies the product |
| Cart or product-view `variant_id` | Use `product_id` for the acted-on V4 variant when needed |
| `query` | `query` for a search card |
| `url` | `url` |
| `input_value`, `accepted_suggestion` | No V4 event fields. Reports do not need this event |

Return the card's `tracking_id` unchanged. Do not build it from the old search ID or product ID. For cart and product-view events, it identifies the selected variant. Supply `product_id` when the shopper acts on another variant, or when no tracking ID is available.

Create the device ID once and store it on the device. Use the same ID across visits and across your search, cart, and purchase events. A native app needs persistent device storage, not a new ID at each launch.

When a click opens a product page, keep its card's `tracking_id`, query, market, and locale with the navigation state. Use the same persistent device ID for later actions. Do not populate V4 events from a stored legacy `search_id` or result position. For a cart action, send the acted-on `product_id` when it differs from the card's selected variant.

For purchases, `transaction_id` becomes `purchase.transaction_id`, and `currency` becomes `purchase.currency`. Convert parallel `transaction_product_ids`, `prices`, and `quantities` into `purchase.items[]` entries with `sku`, `price`, and `quantity`. The transaction product ID is the SKU by default. See [Purchases](https://docs.depict.ai/api-v4/events.md#purchases).

Check both the HTTP status and `rejected` in the response. HTTP 200 can include rejected lines. A positive `accepted` count confirms validation, not report attribution. Depict does not remove duplicate events by `event_id`. Send each shopper action only once. See [Events](https://docs.depict.ai/api-v4/events.md).

The Shopify app's search reports do not yet count clicks, add to carts, or orders from V4 events alone. We are working on this.

## Native mobile apps

Native iOS and Android apps can use the same `browse`, `suggest`, and `events` endpoints. V4 uses HTTPS and JSON responses. Events use NDJSON. No API key or Depict SDK is required. Use your app's HTTP client.

Native HTTP clients do not apply browser CORS rules or need an `Origin` header. JavaScript inside a WebView still follows browser CORS rules. Select `market` and `locale` from `context`, as for the web integration.

The app must supply the [event fields](https://docs.depict.ai/api-v4/events.md#fields):

* Generate `event_id` and `ts` for each action. Send `ts` as an ISO timestamp with an offset.
* Send `type`, `market`, and `session_id`. Optional `locale` identifies the language.
* Use a persistent device ID for `session_id`. Store it on the device and reuse it across visits and app launches.
* Return the card's `tracking_id` unchanged on impressions and clicks. Follow the event reference for cart, product-view, and purchase fields.

These are client responsibilities in both browser and native integrations. A browser does not supply these event fields automatically. The published contract requires no special `User-Agent` value.

For tests, suppress tracking on content reads and validate event payloads locally. Do not send test events to the live API. The `track: false` header does not suppress event writes.

## Worked examples

Replace `acme` with your merchant name. Select a market and locale from your own context. The first example suppresses tracking on product reads. Remove that header for real shopper requests.

For test reads, a browser can send the `track: false` header.

### Search and the next page

```javascript theme={null}
const merchant = "acme";
const base = `https://api.depict.ai/v4/${encodeURIComponent(merchant)}`;

async function read(endpoint, parameters = {}) {
  const query = Object.entries(parameters).map(([key, value]) => {
    const encoded = Array.isArray(value)
      ? value.map(encodeURIComponent).join(",")
      : encodeURIComponent(value);
    return `${encodeURIComponent(key)}=${encoded}`;
  }).join("&");
  const response = await fetch(`${base}/${endpoint}?${query}`, {
    headers: { track: "false" }, // Test reads only; remove for shoppers.
  });
  const body = await response.json();
  if (!response.ok) throw new Error(body.error?.message ?? `HTTP ${response.status}`);
  return body;
}

const context = await read("context");
const market = context.markets.find((item) =>
  item.countries?.some((country) => country.code.toLowerCase() === "se")
);
if (!market) throw new Error("Choose a market from context.markets.");
const locale = market.default_locale; // Or another value from market.locales.
const parameters = {
  market: market.key,
  locale,
  query: "jacket",
  limit: "30",
  include: ["facets", "sorts", "content", "attributes"],
};

const firstPage = await read("browse", parameters);
const nextPage = firstPage.cursor
  ? await read("browse", { ...parameters, cursor: firstPage.cursor })
  : null;
const products = [...firstPage.products, ...(nextPage?.products ?? [])];
console.log(products, firstPage.facets, firstPage.content);
```

Keep each card's `tracking_id` with that card. Keep its query, market, and locale for later events. A changed search starts without a cursor.

### One product click

The function below uses `base`, `market`, `locale`, and `parameters` from the search example. Call it for a real shopper click. Do not call it as a test against the live API: the `track: false` header does not suppress event writes.

```javascript theme={null}
async function sendProductClick(card, deviceId) {
  const event = {
    event_id: crypto.randomUUID(),
    type: "click",
    market: market.key,
    locale,
    session_id: deviceId, // Your persistent device ID, not a visit ID.
    ts: new Date().toISOString(),
    tracking_id: card.tracking_id,
    query: parameters.query,
  };
  const response = await fetch(`${base}/events`, {
    method: "POST",
    headers: { "Content-Type": "application/x-ndjson" },
    body: `${JSON.stringify(event)}\n`,
  });
  const result = await response.json();
  if (!response.ok || result.rejected !== 0 || result.accepted !== 1) {
    throw new Error(`Click rejected: ${JSON.stringify(result)}`);
  }
  return result;
}
```

Pass the clicked card and the same persistent device ID used by your other events. Do not generate a new device ID inside this function.

## Prompt for a coding agent

Copy this prompt into your coding agent and replace `{merchant}` with your store's name in Depict.

```text theme={null}
Migrate this codebase's product search from the Shopify search app API to Depict's V4 API.
Inspect the web app and mobile app separately. Both use the same HTTP API contract.
Ask for the merchant name if it is not configured. Replace {merchant} in every path with that name.

Read these pages first. Follow them if this prompt differs:
- Migration guide: https://docs.depict.ai/api-v4/upgrade-shopify-search
- Endpoints: https://docs.depict.ai/api-v4/endpoints
- Filters and facets: https://docs.depict.ai/api-v4/filters
- Product fields: https://docs.depict.ai/api-v4/contract
- Events: https://docs.depict.ai/api-v4/events
- Markets and locales: https://docs.depict.ai/api-v4/introduction

Step 1. Find every old API call before changing code:
- POST https://runway.depict.ai/search_v2
- GET https://runway.depict.ai/autocomplete_v2
- POST https://runway.depict.ai/events
- Any search-reporting proxy URL or fallback.
List the files, request fields sent, and response fields read for each client.
Report missing mobile-app source or unknown calls. Do not assume its integration matches the web app.

Step 2. Replace search with GET or POST https://api.depict.ai/v4/{merchant}/browse.
- Read valid markets and locales from https://api.depict.ai/v4/{merchant}/context.
- Send query. Select market and locale from that context. V4 needs no API key.
- Parse one JSON object. Products are in products; remove the old stream parser.
- Send limit explicitly. V4 defaults to 24. Use 30 to retain the old default page size.
- Start without a cursor. Send each response's cursor unchanged to get the next page.
- Keep the query, market, locale, filters, sort, sections, and limit unchanged between pages.
- Stop when there is no cursor. Keep client history for previous pages; do not convert page numbers to cursors.
- Reset the cursor when any search input changes.
- Convert filters to filter_by syntax. Use returned facets for field names, values, and counts.
- Request include=facets,sorts,content when those sections are needed. Named sections replace the default facets and sorts.
- In GET requests, encode each include value separately and keep literal commas between values. In POST bodies, use an array.
- Use returned sorts for available sort fields and orders.
- Map product fields as the guide describes: group_id, variants[].product_id, selected, title, images, slug, price, and in_stock.
- Keep IDs as strings. Resolve slug through the storefront's product routes and locale root.
- Read price.amount and optional price.compare_at in major currency units, using the response currency.
- Request configured display attributes with include=attributes. Do not assume every old field or tag is present.

Step 3. Replace autocomplete with https://api.depict.ai/v4/{merchant}/suggest.
Render query and listing suggestions as the guide describes. Remove the old completion-markup parser.
For the start view, use separate empty-query suggest and queryless, listing-free browse requests.

Step 4. Replace tracking with POST https://api.depict.ai/v4/{merchant}/events.
- Send NDJSON, one event per line. Use the supported event types and fields from the guide.
- Return each product card's tracking_id unchanged for impressions and clicks.
- Supply event_id, ts, market, and a persistent device ID in session_id. Keep that ID stable across visits or app launches.
- Replace the old event sender with the V4 sender for each migrated action. Send each shopper action only once.
- Check the HTTP status and rejected count. Do not treat accepted as proof of attribution.

Step 5. Test before enabling shopper traffic.
- For test reads, a browser can send the track: false header.
- Test results, empty product responses, paging to the end, filters, sorting, suggestions, and the start view.
- Check each required market and language, plus prices, stock, product links, and images.
- Test click payloads with local mocks and the published event schema. Do not send test events to the live API.
- The track: false header suppresses tracking on content reads; it does not suppress event writes.

Keep the search UI unchanged. Remove old API calls and reporting-proxy fallbacks from the migrated integration.
Report any feature used by this codebase that the guide lists under "Not available yet".
Summarize the changes, test results, and unresolved requirements before asking to enable shopper traffic.
```

## Not available yet

The Shopify app's search reports do not yet count clicks, add to carts, or orders from V4 events alone. We are working on this.

| Old feature | Current V4 limit |
| - | - |
| `autocomplete_accept`, `input_value`, `accepted_suggestion` | V4 has no event for accepted suggestions. Reports do not need this event |
| `empty_state_suggestion_click`, `follow_up_suggestion_click`, `view_all_click`, `user_feedback`, `search_error_shown` | No corresponding event types |
| Page views of pages other than product pages | No corresponding event type |
| Numbered pages, page jumps, `has_prev_page` | Use cursors and client page history |
| `is_fallback`, `n_hits_approximate` | No identical flags. Use the documented `keyword_matched` and optional `total` meanings |
| `**` completion markup | Render typed suggestions; no equivalent completion markup |
| `content_meta`, content `vector_distance`, `debug_info`, `facet_counts_contract` | No matching response fields |
| A single combined empty-state response and its `localized_strings` | Use separate product and suggestion reads; keep interface text in the client |
| Fixed `is_bestseller`, `is_new`, `is_variable_price`, `published_or_created_at` fields | No fixed fields with those names. Check configured display attributes instead |

## Before you switch

Check your own market and language list, required product attributes, cart IDs, URLs, filters, and cursor paging. Check suggestions and the start view separately.

For tests, suppress tracking on content requests and do not send events. For real shopper actions, remove test settings and verify the reports you need. A successful content request does not verify event attribution. See [Tracking tests](https://docs.depict.ai/api-guide/tracking/introduction.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.