Create a new Product Image

Create a new product image

Script shopify Verified

by hugo697 ยท 11/8/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 396 days ago
1
type Shopify = {
2
  token: string;
3
  store_name: string;
4
};
5
/**
6
 * Create a new Product Image
7
 * Create a new product image
8
 */
9
export async function main(
10
  auth: Shopify,
11
  api_version: string = "2023-10",
12
  product_id: string,
13
  body: {
14
    image?: {
15
      attachment?: string;
16
      filename?: string;
17
      metafields?: {
18
        key?: string;
19
        namespace?: string;
20
        value?: string;
21
        value_type?: string;
22
        [k: string]: unknown;
23
      }[];
24
      position?: number;
25
      [k: string]: unknown;
26
    };
27
    [k: string]: unknown;
28
  }
29
) {
30
  const url = new URL(
31
    `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/products/${product_id}/images.json`
32
  );
33

34
  const response = await fetch(url, {
35
    method: "POST",
36
    headers: {
37
      "Content-Type": "application/json",
38
      "X-Shopify-Access-Token": auth.token,
39
    },
40
    body: JSON.stringify(body),
41
  });
42
  if (!response.ok) {
43
    const text = await response.text();
44
    throw new Error(`${response.status} ${text}`);
45
  }
46
  return await response.json();
47
}
48