Trying To Write A Script Using Shopify Admin API And GraphQL In Order To Extract Store Information

conradspencer
Shopify Partner
9 0 1

 

 

import requests

shop_url = 'https://STORE_URL/admin/api/2023-07/graphql.json'
access_token = 'TOKEN'

def fetch_data():
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }

    # GraphQL query to retrieve data
    query = """
        {
          orders(first: 100, query: "processed_at:>=2023-07-14T00:00:00Z processed_at:<=2023-07-15T00:00:00Z") {
            edges {
              node {   
                paymentGatewayNames
                physicalLocation {
                    name
                }
                name
                createdAt
                __typename
                currentTotalPriceSet {
                  shopMoney {
                    amount
                    currencyCode
                  }
                }
                totalRefundedSet {
                  shopMoney {
                    amount
                  }
                }
               netPaymentSet {
                shopMoney {
                  amount
                }
              }
              totalPriceSet {
                shopMoney {
                  amount
                }
              }
              }
            }
          }
        }
    """


    response = requests.post(shop_url, headers=headers, json={'query': query})

    if response.status_code == 200:
        data1 = response.json()
        print(data1)

    else:
        print(f"Failed to fetch data. Status code: {response.status_code}")
        return []


data1 = fetch_data()

 



 

This script returns the error:
 
Failed to fetch data. Status code: 401
 
If anyone could help it would be much appreciated!
Replies 11 (11)

SBD_
Shopify Staff
1829 269 406

Hey @conradspencer 

 

Which store information specifically?

 

401 indicates an authorization issue. The access token isn't valid, or isn't being passed correctly. Try replacing `Authorization: Bearer {access_token}` with `X-Shopify-Access-Token: {access_token}`

Scott | Developer Advocate @ Shopify 

conradspencer
Shopify Partner
9 0 1

I am trying to retrieve:

  • Net payment
  • total_payment
  • refunded_payments
  • gross_payments
  • transaction
  • day
  • order_number
  • pos_location
  • payment_method

I think the issue is that the token isn't being passed correctly. 

 

 

SBD_
Shopify Staff
1829 269 406

Any luck swapping out the header? (Try replacing `Authorization: Bearer {access_token}` with `X-Shopify-Access-Token: {access_token}`)

Scott | Developer Advocate @ Shopify 

conradspencer
Shopify Partner
9 0 1

Unfortunately not.

SBD_
Shopify Staff
1829 269 406

Hey @conradspencer 

 

I had success with the following code:

 

import requests

shop_url = 'https://{store}.myshopify.com/admin/api/2023-07/graphql.json'
access_token = '...'

def fetch_data():
    headers = {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': access_token
    }

    # GraphQL query to retrieve data
    query = """
        {
          orders(first: 10) {
            edges {
              node {   
                paymentGatewayNames
                physicalLocation {
                    name
                }
                name
                createdAt
                __typename
                currentTotalPriceSet {
                  shopMoney {
                    amount
                    currencyCode
                  }
                }
                totalRefundedSet {
                  shopMoney {
                    amount
                  }
                }
               netPaymentSet {
                shopMoney {
                  amount
                }
              }
              totalPriceSet {
                shopMoney {
                  amount
                }
              }
              }
            }
          }
        }
    """


    response = requests.post(shop_url, headers=headers, json={'query': query})

    if response.status_code == 200:
        data1 = response.json()
        print(data1)

    else:
        print(f"Failed to fetch data. Status code: {response.status_code}")
        return []


data1 = fetch_data()

 

Be sure your API token has `read_orders` scope.

 

Scott | Developer Advocate @ Shopify 

conradspencer
Shopify Partner
9 0 1

My API token does indeed have the 'read_orders' scope on but unfortunately this code returns:

Failed to fetch data. Status code: 404
{"errors":"Not Found"}

 The graph QL query itself works within Shopify's built in graph QL app but not externally. I am very lost here as to what is going wrong. 

SBD_
Shopify Staff
1829 269 406

 

Hey @conradspencer 

 

Can you print + share the `shop_url` value?

Scott | Developer Advocate @ Shopify 

conradspencer
Shopify Partner
9 0 1
SBD_
Shopify Staff
1829 269 406

Thanks. That looks like an old version of the API. Try the more recent 2023-07, as in:

 

https://oliverspencer.co.uk/admin/api/2023-07/graphql.json

Scott | Developer Advocate @ Shopify 

conradspencer
Shopify Partner
9 0 1

Sorry, that was a typo on my part. The URL is already set to https://oliverspencer.co.uk/admin/api/2023-07/graphql.json but the 404 error persists. Any ideas would be much appreciated.

SBD_
Shopify Staff
1829 269 406

That looks fine 🤔 The only way I can get a 404 is by using GET instead of POST.

 

Does curl work for you? Also try using the myshopify domain instead.

curl -X POST \
https://{store}.myshopify.com/admin/api/2021-07/graphql.json \
-H 'Content-Type: application/json' \
-H 'X-Shopify-Access-Token: {password}' \
-d '{
  "query": "{shop{name}}"
}'

 

 

 

Scott | Developer Advocate @ Shopify