What's your biggest current challenge? Have your say in Community Polls along the right column.
Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

State list Shopify StoreFront

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
451 31 47

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    |      Shoplock Hide Pages/Collections

Need a developer?  Just visit MageComp website