0

Search Product Variants

by
Published Nov 8, 2023

Search product variants across all products by SKU, barcode, product, title or inventory.

Script shopify Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 2 hours ago
1
//native
2

3
/**
4
 * Search Product Variants
5
 * Search product variants across all products with Shopify's search syntax (e.g. `sku:ABC-1`, `barcode:0123`, `product_id:123`, `title:Large`, `inventory_quantity:<5`). Leave query empty to list all variants. Returns one page; pass pageInfo.endCursor as after for the next.
6
 */
7
export async function main(
8
  auth: RT.Shopify,
9
  query: string | undefined,
10
  sort_key:
11
    | "SKU"
12
    | "TITLE"
13
    | "FULL_TITLE"
14
    | "NAME"
15
    | "POSITION"
16
    | "INVENTORY_QUANTITY"
17
    | "POPULAR"
18
    | "ID"
19
    | "RELEVANCE"
20
    | undefined,
21
  reverse: boolean | undefined,
22
  first: number | undefined,
23
  after: string | undefined
24
) {
25
  const response = await fetch(
26
    `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
27
    {
28
      method: "POST",
29
      headers: {
30
        "X-Shopify-Access-Token": auth.token,
31
        "Content-Type": "application/json",
32
        Accept: "application/json",
33
      },
34
      body: JSON.stringify({
35
        query: `query ($first: Int!, $after: String, $query: String, $sortKey: ProductVariantSortKeys, $reverse: Boolean) { productVariants(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { id legacyResourceId title displayName sku price compareAtPrice position inventoryQuantity inventoryPolicy availableForSale createdAt updatedAt selectedOptions { name value } barcodes(first: 5) { nodes { value type } } inventoryItem { id tracked } product { id title handle status } } pageInfo { hasNextPage endCursor } } }`,
36
        variables: {
37
          first: first || 50,
38
          after: after || undefined,
39
          query: query || undefined,
40
          sortKey: sort_key || undefined,
41
          reverse: reverse || undefined,
42
        },
43
      }),
44
    }
45
  )
46

47
  if (!response.ok) {
48
    throw new Error(`${response.status} ${await response.text()}`)
49
  }
50

51
  const { data, errors } = await response.json()
52
  if (errors) {
53
    throw new Error(JSON.stringify(errors))
54
  }
55

56
  return data.productVariants
57
}
58

Other submissions
  • Submitted by hugo697 Typescript (fetch-only)
    Created 528 days ago
    1
    type Shopify = {
    2
      token: string;
    3
      store_name: string;
    4
    };
    5
    /**
    6
     * Retrieves a list of product variants
    7
     * Retrieves a list of product variants. Note: As of version 2019-10, this endpoint implements pagination by using links that are provided in the response header. Sending the page parameter will return an error. To learn more, see Making requests to paginated REST Admin API endpoints.
    8
     */
    9
    export async function main(
    10
      auth: Shopify,
    11
      api_version: string = "2023-10",
    12
      product_id: string,
    13
      limit: string | undefined,
    14
      presentment_currencies: string | undefined,
    15
      since_id: string | undefined,
    16
      fields: string | undefined
    17
    ) {
    18
      const url = new URL(
    19
        `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/products/${product_id}/variants.json`
    20
      );
    21
      for (const [k, v] of [
    22
        ["limit", limit],
    23
        ["presentment_currencies", presentment_currencies],
    24
        ["since_id", since_id],
    25
        ["fields", fields],
    26
      ]) {
    27
        if (v !== undefined && v !== "") {
    28
          url.searchParams.append(k, v);
    29
        }
    30
      }
    31
      const response = await fetch(url, {
    32
        method: "GET",
    33
        headers: {
    34
          "X-Shopify-Access-Token": auth.token,
    35
        },
    36
        body: undefined,
    37
      });
    38
      if (!response.ok) {
    39
        const text = await response.text();
    40
        throw new Error(`${response.status} ${text}`);
    41
      }
    42
      return await response.json();
    43
    }
    44