State list Shopify StoreFront

masabmehmood
Visitor
2 0 0

Hi 
I am facing an issue with fetching the state list because i can't find any query or mutation for which I get the state list just as the localization query in which countries can be fetched

Reply 1 (1)

magecomp
Shopify Partner
264 20 32

Hello @masabmehmood 

 

try this

 

 

import requests

def get_state_list(country_code):
    """
    Gets the state list for a given country.

    Args:
        country_code: The two-letter code for the country.

    Returns:
        A list of states.
    """

    url = 'https://api.shopify.com/admin/graphql'
    headers = {
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type': 'application/json',
    }

    body = {
        'query': """
            {
                localization(countryCode: "%s") {
                    states {
                        name
                    }
                }
            }
        """ % country_code,
    }

    response = requests.post(url, headers=headers, data=json.dumps(body))

    if response.status_code == 200:
        data = response.json()
        states = data['data']['localization']['states']
        return states
    else:
        raise Exception('Error getting state list: {}'.format(response.status_code))

 

 


For example, to fetch the state list for the United States, you would use the following code:

 
states = get_state_list('US')
Helping voluntarily. Please like and accept the solution if it helps. Thanks!
Our Bestseller Shopify Apps    |      Mobile App Builder by MageComp    |      Limit Qty Purchase

Need a developer?  Just visit MageComp website