Shopify JSON API example using Python Requests

Shopify API XML and JSON example using Python Requests

I didn’t find any full examples of using the Shopify API in either XML or JSON.

I tried using the Shopify Python library but had trouble identifying the currently saved one to many objects (the Product Variants).

I could easily upload NEW variants, but I could not tell which python object variants received which shopify IDs which I absolutely needed as I was using the API for two way synchronization (pushing and pulling changes).

To put the long story short, the culprit was not having the correct Content-Type header for PUT and POST requests.

Using text/json, shopify was returning an unhelpful 500 error with the error message: “Errors: error” – not helpful! I started wondering if I was using the wrong urls… their template suggesting admin/#{id}.json was a bit confusing too. Why not just write admin/{id}.json ?

Set up authentication

Using the python requests library makes this extremely easy.

request = requests.Session(auth=(settings.SHOPIFY_API_KEY, settings.SHOPIFY_API_PASSWORD))
print json.loads(request.get('http://myshop.myshopify.com/admin/assets.json').content)

Create a product

payload = '''{
	  "product": {
	    "body_html": "<strong>Good snowboard!</strong>",
	    "product_type": "Snowboard",
	    "title": "Burton Custom Freestlye 151",
	    "variants": [
	      {
	        "price": "10.00",
	        "option1": "First"
	      },
	      {
	        "price": "20.00",
	        "option1": "Second"
	      }
	    ],
	    "vendor": "Burton"
	  }
	}'''

response = request.post('http://myshop.myshopify.com/admin/products', 
	data=payload,
	headers={'
		'Content-Type': 'application/json', # this is the important part.
	},)
print response.status_code, response.content

Modify an existing product

payload = '''{
	  "product": {
	    "published": false,
	    "id": 632910392
	  }
	}'''
response = request.put('http://myshop.myshopify.com', data=payload, headers={'Content-Type': 'application/json'})

6 Comments

  1. jpatel3 says:

    requests is good easy to use library. nice post!

  2. Ratan Kumar says:

    getting :
    TypeError: __init__() got an unexpected keyword argument ‘auth’

    when tring this :
    request = requests.Session(auth=(settings.SHOPIFY_API_KEY, settings.SHOPIFY_API_PASSWORD))

    1. Freak Developer says:

      I am getting same error, Please help!

  3. If you are on Python 3 you might be interested in https://github.com/masom/shopify-trois 🙂

  4. GAay says:

    auth was never defined. And the author has disappeared….rendering this post useless.

  5. Felix says:

    i think this is how it work (you have to define URL, KEY, PASSWORD:
    request=requests.get(URL, auth=(KEY, PASSWORD))
    print (request.text)

Leave a reply to Felix Cancel reply