CleverPatrick
CleverPatrick

Reputation: 9491

Shopify GraphQL API: Create a Basic Product and Set the Price with 2024-10 API version

Old versions of the Shopify GraphQL productCreate mutation seemingly offered a variants field where you could set the price of the product you were creating.

The latest version as of writing this (2024-10) does not seem to have this option.

Is there a way to create a basic product with only one variant (or no variants!) and set a price in a single operation?

And if it must be done in two operations? What is the correct second mutation?

Upvotes: -1

Views: 146

Answers (2)

Tirth Mehta
Tirth Mehta

Reputation: 1

Create the Product: The first operation in your code is creating the product in Shopify. You use the productCreate mutation to create the product with the required details such as the title, vendor, and status (which is set to "DRAFT" in your example).

const productCreateMutation = gql`
  mutation productCreate($product: ProductCreateInput!) {
    productCreate(product: $product) {
      product { id title status }
      userErrors { field message }
    }
  }
`;

// Example product input
const productInput = {
  title: product.Description || "Untitled Product",
  vendor: product.SupplierCode || "Unknown Vendor",
  status: "DRAFT", // Product is created in draft mode
  tags: ["importLStoSHOP"],
};

const productCreateResponse = await client.request(productCreateMutation, { product: productInput });

Above step creates the product but does not include any price or variant details.

Now, Create the Variant and Set the Price: Once the product is created, you can add a variant to it using the productVariantsBulkCreate mutation. This is where you set the price, SKU, barcode, and other variant-specific information.

const productVariantsBulkCreateMutation = gql`
  mutation productVariantsBulkCreate($productId: ID!, $strategy: ProductVariantsBulkCreateStrategy, $variants: [ProductVariantsBulkInput!]!) {
    productVariantsBulkCreate(productId: $productId, strategy: $strategy, variants: $variants) {
      product { id }
      productVariants { id inventoryItem { id } }
      userErrors { field message }
    }
  }
`;

// Example variant data
const variants = [{
  inventoryItem: { sku: product.PartNumber || "UNKNOWN-SKU" },
  price: product.CurrentActivePrice || 0.0, // Set the price here
  barcode: product.UPC || null,
}];

const variantsResponse = await client.request(productVariantsBulkCreateMutation, {
  productId,
  strategy: "REMOVE_STANDALONE_VARIANT",
  variants,
});

Above step creates the variant for the product and includes the price for that variant.

Upvotes: -1

Developer Nilesh
Developer Nilesh

Reputation: 560

@CleverPatrick , We need to follow these steps:

First, create a product for ID, then add a variant with price, though productVariantsBulkCreate is preferred even for single variants.

Upvotes: 1

Related Questions