0

Retrieves a list of product variants

by
Published Nov 8, 2023

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.

Script shopify Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 416 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