Trying to write a script using Shopify Admin API and GraphQL in order to extract customer names

import os
import requests
from dotenv import load_dotenv, find_dotenv
import shopify

load_dotenv(find_dotenv())

api_key = 'API_KEY'
password = 'API_SECRET_KEY'
shop_url = 'https://{SHOP_URL}/admin/api/2023-04/graphql.json'
token = os.getenv('TOKEN')

session = shopify.Session(shop_url, '2023-04')
session.token = token

shopify.ShopifyResource.activate_session(session)

def fetch_customer_name():
    headers = {
        'Content-Type': 'application/graphql',
        'X-Shopify-Access-Token': token
    }

    #GraphQL query to retrieve customer names
    query = """
    {
      shop {
        Customer(first: 10) {
          edges {
            node {
              orderNumber
            }
          }
        }
      }
    }
    """

    response = requests.post(shop_url, headers=headers, data=query)

    if response.status_code == 200:
        data = response.json()
        customer_name = [edge['node']['CustomerName'] for edge in data['data']['shop']['Customer']['edges']]
        return customer_name
    else:
        print(f"Failed to fetch customer names. Status code: {response.status_code}")
        return []

customer_name = fetch_customer_name()
print(customer_name)

The script returns the error:

Failed to fetch customer names. Status code: 401
[]

If anyone knows where I am going wrong any help would be massively appreciated because it is killing me!

Hey @conradspencer

401 indicates an issue with authorization. Can you log os.getenv(‘TOKEN’) to make sure the token is correct?

hi @SBD ,

I have, the token is correct, hence why it is so frustrating!

If you have any other ideas please do let me know. Thanks.

I’m a little rusty with Python but had success with this code:

import requests

shop_url = 'https://{shop}.myshopify.com/admin/api/2023-04/graphql.json'

def fetch_customer_name():
  headers = {
      'Content-Type': 'application/graphql',
      'X-Shopify-Access-Token': '{token}'
  }

  #GraphQL query to retrieve customer names
  query = """
    {
      customers(first: 10) {
        nodes {
          displayName
        }
      }
    }
  """

  response = requests.post(shop_url, headers=headers, data=query)
  
  if response.status_code == 200:
      data = response.json()
      print(data)
  else:
      print(f"Failed to fetch customer names. Status code: {response.status_code}")
      return []

customer_name = fetch_customer_name()

Thank you so much!

1 Like