0
Retrieve a list of products belonging to a collection
One script reply has been approved by the moderators Verified

Retrieve a list of products belonging to a collection. 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.. The products returned are sorted by the collection's sort order.

Created by hugo697 655 days ago Viewed 22466 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 655 days ago
1
type Shopify = {
2
  token: string;
3
  store_name: string;
4
};
5
/**
6
 * Retrieve a list of products belonging to a collection
7
 * Retrieve a list of products belonging to a collection. 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.. The products returned are sorted by the collection's sort order.
8
 */
9
export async function main(
10
  auth: Shopify,
11
  api_version: string = "2023-10",
12
  collection_id: string,
13
  limit: string | undefined
14
) {
15
  const url = new URL(
16
    `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/collections/${collection_id}/products.json`
17
  );
18
  for (const [k, v] of [["limit", limit]]) {
19
    if (v !== undefined && v !== "") {
20
      url.searchParams.append(k, v);
21
    }
22
  }
23
  const response = await fetch(url, {
24
    method: "GET",
25
    headers: {
26
      "X-Shopify-Access-Token": auth.token,
27
    },
28
    body: undefined,
29
  });
30
  if (!response.ok) {
31
    const text = await response.text();
32
    throw new Error(`${response.status} ${text}`);
33
  }
34
  return await response.json();
35
}
36