Authenticate with OAUTH2 and Download Device Data - Python

About this Python Sample App

This sample app is a very simple Python application that does the following:

  1. Launches your system browser to Authenticate using OAUTH2
  2. Saves the credentials to the filesystem
  3. Launches a simple local flask app to allow you to then download device data.

There are comments in the code that describe high-level what is happening.

You can copy the sample code below. Ensure that you install the referenced imported packages that are not part of the standard library.

How to Run

  1. Install the requirements with:

    pip install flask requests
  2. Run the Sample App with:


Problems Running the Code?

If you have any problems running the code then reach out to us in our Community Forum.

Sample Code

from flask import Flask, request
import pickle
import requests
import json
import webbrowser

app = Flask(__name__)

# Insert your own info here as you defined when you created your APP
REDIRECT_URI = "" # for this example APP, this needs to be your redirect URI
STATE = ""

# A webpage that is amazing in its simplicity
<p>You have been Authenticated with the API.</p>
<p>What do you want to do now?</p>
<form action="/inventory" target="_blank">
  <input type="submit" value="Get Inventory">
<p>Note: Pulling down all of your inventory may take some time.  Check your console for the progress.</p>

total_inventory = None

def authorize():

    temp_code = request.args.get('code','')

    # Now lets get our authorization token
    url = ""
    body = {
        'grant_type': "authorization_code",
        'code': temp_code,
        'redirect_uri': REDIRECT_URI,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
         # 'Content-Type': "application/x-www-form-urlencoded"

    response = requests.request("POST", url, data=body)
    response = json.loads(response.text)

    # don't do this in a real app obviously
    with open('temp', 'wb') as f:
        pickle.dump(response, f)


def get_full_inventory():
    global total_inventory

    with open('temp', 'rb') as f:
        response = pickle.load(f)

    access_token = response['access_token']

    url = ""
    headers = {
        'Content-Type': "application/json",
        'Authorization': f"Bearer {access_token}",

    start_index = 1
    total_inventory = []
    total_results = -1

    while total_results != 0:

        querystring = {"startIndex": f"{start_index}",
                       "count": "1000"}

        response = requests.request("POST", url, headers=headers, params=querystring)
        inventory = json.loads(response.text)
        total_results = inventory['totalResults']
        total_inventory += inventory['resources']

        start_index += 1
        print(f'Devices Downloaded: {len(total_inventory)}')

    with open('inventory.json', 'w+') as f:
        f.write(json.dumps(total_inventory, indent=4, sort_keys=True))


if __name__ == '__main__':