How to create a cart on the shopify storefront API

How to create a cart on the shopify storefront API

marcusps1
Shopify Partner
1 0 2
 

I am building a headless shopify site using remix. Fro reading the documentation on storefront in order for you to do a a checkout you must create a cart and send a post request to the api.

I am sending this graphql request which I found off the official docs to create a cart https://shopify.dev/api/examples/cart. Where the merchadise id is the id I get back from when i call get products

 

mutation {
  cartCreate(
    input: {
      lines: [
        {
          quantity: 2
          merchandiseId: "gid://shopify/ProductVariant/6964601651340"
        }
      ]
      attributes: { key: "cart_attribute", value: "This is a cart attribute" }
    }
  ) {
    cart {
      id
      createdAt
      updatedAt
      lines(first: 10) {
        edges {
          node {
            id
            merchandise {
              ... on ProductVariant {
                id
              }
            }
          }
        }
      }


    }
  }
}

Here is a response of getProducts

{
  "node": {
    "id": "gid:\/\/shopify\/Product\/6964601651340",
    "handle": "vans-authentic-butterfly-true-white-black",
    "title": "VANS | AUTHENTIC (BUTTERFLY) TRUE | WHITE \/ BLACK",
    "description": "The forefather of the Vans family, the Vans Authentic was introduced in 1966 and nearly 4 decades later is still going strong, its popularity extending from the original fans - skaters and surfers to all sorts. The Vans Authentic is constructed from canvas and Vans' signature waffle outsole construction.",
    "variants": {
      "edges": [
        {
          "node": {
            "price": "109.95"
          }
        }
      ]
    }
  }
}

If I change "gid://shopify/ProductVariant/6964601651340" to gid://shopify/Product/6964601651340 - i get invalid id. But if I make the request with productVariant I get the response

{
  "data": {
    "cartCreate": {
      "cart": null
    }
  }
}

what am I doing wrong - how do i create a cart?

Reply 1 (1)

cheap_science
Visitor
1 0 1

Hi, you need to retrieve the variant id instead of the product id. Unfortunately, this part of the shopify documentation is poorly written.