I’m still pretty new to using Shopify’s GraphQL API and GPQL in general but I would like some help if possible on just how you would create a product with media and variants that have stock pricing etc etc. I’m using 2024-04 and from what I understand in the documentation I should be able to do this:
I’ve setup this mutation
mutation CreateProduct($input: ProductInput!, $media: [CreateMediaInput!]) {
productCreate(input: $input, media: $media) {
product {
id
options {
id
name
values
}
variants(first: 10) {
nodes {
id
title
price
selectedOptions {
name
value
}
inventoryItem {
id
}
}
}
media(first: 10) {
nodes {
alt
mediaContentType
preview {
status
}
}
}
metafields(first: 10) {
edges {
node {
type
namespace
key
value
}
}
}
}
userErrors {
field
message
}
}
}
And then its being used here:
for (let i = 0; i < productsData.length; i += batchSize) {
const batch = productsData.slice(i, i + batchSize);
const batchResults = await Promise.all(
batch.map(async (product) => {
const variantInputs = product.variants.map((variant) => ({
price: variant.price,
sku: variant.sku,
inventoryManagement: variant.inventoryManagement || "SHOPIFY",
inventoryPolicy: variant.inventoryPolicy || "DENY",
inventoryQuantities: [
{
availableQuantity: variant.inventoryQuantity,
locationId: "gid://shopify/Location/75778687232",
},
],
}));
const mediaInputs = product.images.map((image) => ({
originalSource: image.src,
alt: image.alt || "",
mediaContentType: "IMAGE",
}));
// Create the product with variants included
const productResponse = await shopifyAPI.post(
"",
JSON.stringify({
query: productCreateMutation,
variables: {
input: {
title: product.title,
bodyHtml: product.bodyHtml,
vendor: product.vendor,
productType: product.productType,
variants: {
variants: variantInputs,
},
media: {
media: mediaInputs,
},
metafields: [
{
namespace: "custom",
key: "sync_from_api",
type: "boolean",
value: "true",
},
],
},
},
})
);
if (!productResponse.data || productResponse.data.errors) {
console.error("GraphQL Error:", productResponse.data.errors);
return null;
}
if (productResponse.data.data.productCreate.userErrors.length > 0) {
console.error(
"User Errors:",
productResponse.data.data.productCreate.userErrors
);
return null;
}
return {
productId: productResponse.data.data.productCreate.product.id,
variants:
productResponse.data.data.productCreate.product.variants.edges.map(
(edge) => edge.node
),
};
})
);
results = results.concat(batchResults);
await sleep(delay);
}
Is this the correct way of doing so?