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:

    python app.py
    

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
CLIENT_ID = ""
CLIENT_SECRET = ""
REDIRECT_URI = "http://127.0.0.1:5000/" # for this example APP, this needs to be your redirect URI
STATE = ""

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

webbrowser.open(f'https://daas.api.hp.com/oauth/v1/authorize?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code&scope=Read&state={STATE}')


total_inventory = None


@app.route('/')
def authorize():

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

    # Now lets get our authorization token
    url = "https://daas.api.hp.com/oauth/v1/token"
    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)

    return AMAZING_WEB_PAGE


@app.route('/inventory')
def get_full_inventory():
    global total_inventory

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

    access_token = response['access_token']

    url = "https://daas.api.hp.com/analytics/v1/reports/hwinv/details/type/grid"
    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))

    return AMAZING_WEB_PAGE


if __name__ == '__main__':
    app.run()