Shopify Discounts GraphQL API

Viewed 33

I have two queries, one for fetching automatic discounts and other for fetching code discounts of a shopify store. So is there a way that I can fetch both the discounts on a single query. Also we are letting users search for their discounts by title, so is there any query that returns data based on discount title because I have seen that in products or collections inside the query we can use:

products(first: 10, query: "title:*searched_text*")

These are my queries:

 # for code discounts
query_1 = '''
    {
      codeDiscountNodes (first:10,query:"status:active"){
          edges {
          node {
            id
            codeDiscount {
              __typename
              ... on DiscountCodeBxgy {
              status
              title
            }
            ... on DiscountCodeBasic {
              status
              title
            }
            }
          }
        }
      }
    }
    '''
    
    # for automatic discounts
    query_2 = '''
    {
    automaticDiscountNodes (first: 10) {
      edges {
        node {
          id
          automaticDiscount {
            __typename
            ... on DiscountAutomaticBxgy {
              status
              title
            }
            ... on DiscountAutomaticBasic {
              status
              title
            }
          }
        }
      }
     }
    }
    '''
1 Answers

Welcome to Stack Overflow!

...is there a way that I can fetch both the discounts on a single query?

Yes, and there are two ways to do this:

First, in GraphQL you can bundle queries together into a single string like so:

{
  codeDiscountNodes(first:10) {
    edges {
      node { id }
    }
  }
  automaticDiscountNodes(first:10) {
    edges {
      node { id }
    }
  }
}

Results in:

{
  "data": {
    "codeDiscountNodes": {
      "edges": [
        {
          "node": { "id": "gid://shopify/DiscountCodeNode/10..." }
        }
      ]
    },
    "automaticDiscountNodes": {
      "edges": [
        {
          "node": { "id": "gid://shopify/DiscountAutomaticNode/10..." }
        }
      ]
    }
  }
}

Alternatively, the shopify API provides a general discountNodes endpoint which you can use to request all your discounts together.

{
  discountNodes(first:10) {
    edges {
      node {
        id
      }
    }
  }
}

This approach is more efficient than combining the two queries (check out the extensions.cost.actualQueryCost for each of these solutions).

...is there any query that returns data based on discount title?

No, it does not appear like this API allows you to search by title. You can find the list of query filter parameters in the documentation..

Related