How to submit a valid item to cart/add.json

Solved
jasoncarousel
Excursionist
16 2 2

So the cart/add.json reference says that it needs a minimum of an items list with variant IDs and quantity, like so:

items: [ { id: 36110175633573, quantity: 2 } ]

However, we aren't having any luck submitting a valid add to cart request. The error we are seeing is:

"400 Bad Request: Required parameter missing or invalid: items"

This is what we are submitting in our POST body (pulled directly out of Chrome developer tools making the cart/add.json request, just obfuscating the variant ID):

items: [ { id: 12345678901234, quantity: 1 } ]

Any ideas why this would return the error mentioned above would be greatly appreciated.

We've tried a JSON.stringify version of the same string, but got the same results. We just want to know if we are submitting this request with the right syntax.

 

 

0 Likes
jasoncarousel
Excursionist
16 2 2

Here is the full javascript fetch for the cart add request, in case it helps:

 

            fetch("/cart/add.js", {
                method: 'post',
                body: 'items: [ { id: 12345678901234, quantity: 1 } ]'
            }).then(response => response.json())
                .then(data => processCartAdd(data))
                .catch(error => console.error('Unable to add to cart.', error));

 

0 Likes
jasoncarousel
Excursionist
16 2 2

Also, in case it helps, we are getting the variant ID for cart/add.json from the products.json API. Each time we complete an Excelify feed of new products to Shopify, we request those same new products from products.json (using the created_at_min parameter). From the resulting response, we save the variant ID to our custom app specifically for use in the cart/add.json.

We aren't sure if this is the correct variant ID, since we can't see how to verify the variant ID in the store admin screens for items that only have one variant.

0 Likes
jasoncarousel
Excursionist
16 2 2

Thanks to our launch engineer, we were able to view the variant ID for the specific item we are trying to add to cart, using the .json extension to the listing on Shopify.

We have verified that it is the same variant ID we are trying to submit in the cart add action.

0 Likes
jasoncarousel
Excursionist
16 2 2

This is an accepted solution.

The issue was simply a missing content type header. Here is what we added to make it work:

fetch("/cart/add.js", {
  method: 'post',
  headers: {
    'Content-Type': 'application/json'
  },
  body: 'items: [ { id: 12345678901234, quantity: 1 } ]'
}).then(response => response.json())
.then(data => processCartAdd(data))
.catch(error => console.error('Unable to add to cart.', error));