I want to apply discount coupon code to the cart page, I am trying to use the storefront API cartDiscountCodesUpdate which expect the cart id. How can I get this cart id. Here is what I tried. I have created the webhook cart/create which has payload id in the form of string something like '1eef2aa2c2b2e889ec325db72f0877ec'.
Then I tried calling this id which I got from cart/create response in storefront API cartDiscountCodesUpdate like:
mutation cartDiscountCodesUpdate($cartId: ID!, $discountCodes: [String!]) {
cartDiscountCodesUpdate(cartId: $cartId, discountCodes: $discountCodes) {
cart {
id
}
userErrors {
field
message
}
}
}
Query Varialbe:
{
"cartId": "gid://shopify/Cart/1eef2aa2c2b2e889ec325db72f0877ec",
"discountCodes": [
"64J1ZQMBN9W5"
]
}
But its response with below error. I think its the issue with incorrect cart id. Can anyone help me how to get cart id after the cart is created?
Response from cartDiscountCodesUpdate storefront API.
{
"data": {
"cartDiscountCodesUpdate": {
"cart": null,
"userErrors": [
{
"field": [
"cartId"
],
"message": "The specified cart does not exist."
}
]
}
}
}
Related
How to delete all products via admin api?
To achieve the goal i try to use the Bulk Payloads | Deleting entities
The doc says:
[...] To delete entities, the payload of an operation contains the IDs. [...]
Questions:
to delete all products i have to read first all product.id's?
or is there a alternative way with a type of "wildcard"?
My current request body (using Postman) ...:
{
"delete-product": {
"entity": "product",
"action": "delete",
"payload": []
}
}
... response with (products remains in db):
{
"extensions": [],
"success": true,
"data": {
"delete-product": {
"extensions": [],
"result": []
}
},
"deleted": [],
"notFound": []
}
EDIT #1
With id's provided...:
...
const obj = {
"delete-products": {
"entity": "product",
"action": "delete",
"payload": [
{"id": "73af65014974440b95450f471b3afed8"},
{"id": "784f25a29e034fad9a416923f964ba8a"}
]
}
}
apiClient.request({
"url": "/_action/sync",
"method": "POST",
obj
})
...
... the request fails in class Symfony\\Component\\Serializer\\Encoder\\JsonDecode with message:
detail: "Syntax error"
Debugging the request, payload is missing (empty content):
What is wrong with the configuration of the /api/_action/sync call?
Indeed, what it means is that you will need a low impacting query to get all product id's, store it into a variable & delete them. Use includes:["id"] filter to just get the ID's.
Here is an example of me deleting some products in Postman.
Request body:
{
"delete-product": {
"entity": "product",
"action": "delete",
"payload": {{gen_dynamic_products}}
}
}
Pre-request script (you'll need to adjust this sightly to get your ID's):
const map = new Array(30).fill(0).map((val, index) => {
return { id: pm.environment.get('gen_product_list_sub_' + index) };
});
pm.variables.set('gen_dynamic_products', JSON.stringify(map));
to delete all products i have to read first all product.id's?
Yes, that is what you'll have to do. This is necessary to maintain the extendibility of the platform. The core or other plugins may react to the deletion of products by subscribing to an entity lifecycle event. This event includes the id of the deleted entity. Hence why it is necessary to explicitly provide the ids of the entities in the first place.
I am setting properties when adding to cart.
Ex:
var formdata=[
"items":{
id:123456,
quantity:1
properties:{'flag':true}
}
];
added using api : /cart/add.js
Details I get from cart.js without refresh
response from : /cart/add.js and cart.js
[
{
"id": 32423423423423,
"properties": {
"flag": true
},
"quantity": 1,
"variant_id": 42705234345345,
}
]
The above items get added successfully to cart. After adding I again fetch the cart details and It has this properties value.But when I refresh the page cart items properties does not have any value.
Ex Currently I am getting this only when page is refreshed:
response from cart.js after page refresh
properties:{
Ref: 0
}
What this properties is?
Why is this happening? If worked, will this properties be available on order create webhook? It only disappears when refreshed. Moreover main reason to add this properties is to receive this properties in order-create webhook to distinguish from normal order. If anyone having other alternative please suggest.
Adding a product to the cart like so:
fetch('/cart/add.js', {
method: "post",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
items: [
{
quantity: 1,
id: 33116507373620,
properties: {
'flag': true
}
}
]
})
})
And getting the cart.js like so:
fetch('/cart/add.js').then(res => res.json()).then(res => console.log(res))
Will get you result like so:
{
...
"items": [
{
"id": 33116507373620,
"properties": {
"flag": true
},
"quantity": 1,
...
}
],
...
}
From there on what you are doing to not get this result I'm not sure, since this is working/tested and there is no issue.
Please double check if you are targeting the correct object once you get the cart.js response. (there is no properties direct object, it's under items[0].properties in this case)
Given "user has many links" (what means a link was created by a user) DB entities relations, I want to develop API to fetch links along with users so that the returned data does not contain duplicated users.
In other words, instead of this request:
query {
links {
id
user {
id email
}
}
}
that returns the following data:
{
"data": {
"links": [
{
"id": 1,
"user": {
"id": 2,
"email": "user2#example.com"
}
},
{
"id": 2,
"user": {
"id": 2,
"email": "user2#example.com"
}
}
]
}
}
I want to make a request like this (note the "references" column):
query {
links {
id
userId
}
references {
users {
id
email
}
}
}
that returns associated users without duplicates:
{
"data": {
"links": [
{
"id": 1,
"userId": 2
},
{
"id": 2,
"userId": 2
},
],
"references": {
"users": [
{
"id": 2,
"email": "user2#example.com"
}
]
}
}
}
That should reduce amount of data transferred between client and server that adds a bit of speed boost.
Is there ready common implementation on any language of that idea? (Ideally, seeking for Ruby)
It's not a query or server role to normalize data.
there are no such possibilities in GraphQL specs;
server must return all asked fields within queried [response] structure;
... but you can implement some:
standarized (commonly used) pagination (relay style edges/nodes, nodes only or better both);
query [complexity] weights to promote this optimized querying style - separate problem;
reference dictionary field within queried type;
links {
egdes {
node {
id
title
url
authorId
# possible but limited usage with heavy weights
# author {
# id
# email
# }
}
}
pageInfo {
hasNextPages
}
referencedUsers {
id
email
}
}
where:
User has id and email props;
referencedUsers is [User!] type;
node.author is User type;
Normalizing Graphql client, like Apollo, can easily access cached user fields without making separate requests.
You can render (react?) some <User/> component (within <Link /> component) passing node.authorId as an argument like <User id={authorId} />. User component can useQuery hook with cache-only policy to read user props/fields.
See Apollo docs for details. You should implement this for yourself and document this to help/guide API users.
I want to expose the product metafields in shopify to my Storefront API.
I am referring to following documentation. https://help.shopify.com/en/api/guides/metafields/storefront-api-metafields
Following is the content of my body
mutation($input: MetafieldStorefrontVisibilityInput!) {
metafieldStorefrontVisibilityCreate( input: $input ) {
metafieldStorefrontVisibility {
id
}
userErrors {
field message
}
}
}
Following are the GRAPHQL VARIABLES
{
"input": {
"namespace": "global",
"key": "description_tag",
"ownerType": "PRODUCT"
}
}
Following is the URL
https://posdev07.myshopify.com/admin/api/2019-07/graphql.json
I get following error when I make the request.
{"errors":{"query":"Required parameter missing or invalid"}}
Here is the body
{
"product": {
"id": 1202316036,
"title": "cricket bat for sale",
"variants":[
{
"inventory_quantity": 500
}
]
}
}
This returns the following error
{
"errors": {
"base": [
"The variant 'Default Title' already exists."
]
}
}
But where as the updating the title seems to be working fine. Here is the body
{
"product": {
"id": 1202316036,
"title": "cricket bat for sale"
}
}
I am sure that PUT header(Content-Type: application/json) are set properly. Because updating title does work. How should I go about updating inventory management
ps: I am using POSTMAN for using shopify API
So you do need the variant id otherwise Shopify thinks you are creating a new variant. Also your variants need to have been set up for Shopify to manage their inventory. e.g.
var product = {
product:{
id: productId,
variants: [
{
id:5991257025,
inventory_management : "shopify",
inventory_quantity:20
},
{
id:5991257089,
inventory_management : "shopify",
inventory_quantity:26
}
]
}
};
I'm not sure if you can do multiple variants per call but to update a single variant's inventory quantity you'd do it like:
var payload = JSON.stringify({
variant: {
id: variantId,
inventory_quantity: qty
}
});
and then put that to "https://myshopifydomain/admin/variants/" +variantId + ".json";
possibly all you need to do is add the variant id for each variant you are updating. Your variant ids can be gotten by GETting the json for your items.