How to Get All Orders from Shopify in Python

[This article was first published on Python – Predictive Hacks, and kindly contributed to python-bloggers]. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

Shopify is one of the most famous platforms to set up online shops. As a Data Scientist, I’ve been asked many times to build something integrated into Shopify like automated descriptive analytics of orders, ERP connectors, etc. The first thing we have to do is to get all the information we want from Shopify ie the orders and their Info. In this post, we will show you how you can set up a private app and use it to get all orders in python surpassing its limit of 250 rows.

Create a private APP in Shoppify

First things first, we need to create a private App to get an API URL.

Step 1: Navigate to the left and click on Apps

How to Get All Orders from Shopify in Python 1

Step 2: Scroll all way down and click on Manage Private Apps

How to Get All Orders from Shopify in Python 2

Step 3: Create a new private app

How to Get All Orders from Shopify in Python 3

After you created your app you can get the url we will use in the Example URL placeholder.

 Get All Orders from Shopify in Python

Get All Orders

Now, you should have a URL in the following format:

https://{apikey}:{password}@{hostname}/admin/api/{version}/{resource}.json

We want to get all orders so we need to add some variables in the URL.

  • limit=250, This is the maximum number of orders we can get.
  • fulfillment_status=unfulfilled, We will get all unfulfilled orders so we will use the status unfulfilled. You can remove it and get also the fulfilled orders.
  • since_id=, This means that we want all orders since the order Id we will provide. We will use it to surpass the limit of 250 orders.

The trick here is after every API call to get the oldest order ID and use it for our next call inside the since_id variable. Then, when the API will return less than our limit (250) we stop the loop and return the orders Dataframe.

import pandas as pd
import numpy as np
import re
import requests


def get_all_orders():
    last=0
    orders=pd.DataFrame()
    while True:
        url = f"https://{apikey}:{password}@{hostname}/admin/api/{version}/{resource}.json?limit=250&fulfillment_status=unfulfilled&since_id={last}"
        response = requests.request("GET", url)
        
        df=pd.DataFrame(response.json()['orders'])
        orders=pd.concat([orders,df])
        last=df['id'].iloc[-1]
        if len(df)<250:
            break
    return(orders)



df=get_all_orders()
df.head()
How to Get All Orders from Shopify in Python
 Get All Orders from Shopify in Python

To leave a comment for the author, please follow the link and comment on their blog: Python – Predictive Hacks.

Want to share your content on python-bloggers? click here.