Python & Flask Guide

This program is running on Python 3. You would be required to install Flask and flask-cors, as this program will run with Flask as the web server.

Click here to go to the repository. You can access all the app code and reuse it for your application.

Make sure you have the correct path for all the files in your project folder.

  • For instance, this project folder name will be Python-Demo.
  • Next, create a python file main.py and save it in Python-Demo.
  • Then, you can create 2 new Folder called static and templates inside Python-Demo folder.
  • In Folder templates you can create 3 HTML file, in this program I will call it Start.html, Result.html, and Error.html.
  • Finally in Folder static go ahead and create new Folder called css and save main.css and script.js onto css folder.

Your files path should look like the following,

Installation

pip install flask
pip install flask-cors

Usage

Import package

from flask import Flask, render_template,redirect,request #use Flask package
from urllib.request import Request, urlopen,base64 #use urllib package
from flask_cors import CORS, cross_origin #Use CORS to enable all of HTTP headers mechanism
import json #read json format
import random,string #Import random and string for generating session
from datetime import datetime #get current date

Flask application configuration

app = Flask(__name__)
cors = CORS(app)#CORS configuration for any header to be accessed in HTTP
app.config['CORS_HEADERS'] = 'Content-Type'

Initializing Dictionary to store values

dictionary= {
    "session":"",
    "token" :"",
    "date":[],
    "description":[],
    "status":[],
    "amount":[],
}#dictionary to store value retrieved from https://sandbox.onebrick.io/v1/transaction/list

user_account= {
    "accountHolder":[],
    "accountNumber" :[],
    "accountId":[],
    "balances":{
        "available":"",
        "current":"",
    }
}#dictionary to store value retrieved from https://sandbox.onebrick.io/v1/account/list

user_detail= {
    "accountHolder":"",
    "accountNumber" :"",
    "accountId":"",
    "balances":{
        "available":"",
        "current":"",
    }
}#dictionary to store value retrieved from https://sandbox.onebrick.io/v1/account/detail

#boolean if user uses Jenius Bank
boolean = {
    "isJenius" : False
 }

#jenius dictionary to store jenius transaction and account details
jenius = {
    "jeniusTransactionDetail":[],
    "jeniusAccountDetail":[]
}

base_link variable to access the Brick Sandbox

#Brick Sandbox link
base_link = "https://sandbox.onebrick.io/v1/"

First function to be called when you run the program

#trigger main when program is executed
@app.route("/")
def main():
    #render Start page
    return render_template('Start.html')

Start.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel = "stylesheet" href = "{{ url_for('static', filename='css/main.css') }}">
    <script src="{{url_for('static',filename='script.js')}}"></script>
    <title>Demo</title>
    
</head>


<body>
    <div class="center-page">
        <h2 class="app-name">Money Save App</h2>
        <p class="detail">Welcome to Brick's PFM application. Please think of Money Save as your own application UI when using this demo.</p>
        <div class="button-wrapper">
            <form action ="{{url_for('goto')}}" method ="post" target="popup" onsubmit ="window.open('','popup','width=800, height=800');">
                <input type="submit" value ="Add a Bank Account" style="margin:0px auto"></input>
            </form>
        </div>
    </div>
</body>
</html>

Function goto()

After a form is submitted from the Start.html, it will trigger the POST method to the function goto().

@app.route("/goto",methods=['POST'])
def goto():
    #call function authentication() to get the JWT-public-access-token
    token = authentication()
    #url to access onebrick.io API
    url = base_link+"index?"+"accessToken="+token+"&redirect_url="+"http://localhost:5000/result"
    return redirect(url)#return redirect to call Brick API

Function authentication()

This function will be called later by function goto() to get the account's (JWT) public-access-token

def authentication():
    #change the value XXXXX to your client ID in Brick account
    clientID = "XXXXX"
    #change the value XXXXX to your client Secret in Brick account
    clientSecret = "XXXXX"
    account = clientID +":" +clientSecret
    #perform base 64 encoding for basic authentication
    authorize = "Basic " + base64.b64encode(account.encode()).decode()
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':authorize}
    #retrieve the json value from the link
    request = Request(base_link+'auth/token', headers=header)
    response = urlopen(request).read().decode('utf-8') #if response success, it will return : {"status":200,"message":"OK","data":{"access_token":"public-sandbox-5a002d0b-6437-4233-862a-eb1d8d79cc0f"}}
    data = json.loads(response)['data']
    return data['access_token'] #return only the value "public-sandbox-5a002d0b-6437-4233-862a-eb1d8d79cc0f"

After the URL is called, there will be pop up of Brick API

Once user has sign in to the Financial Institution account, they will be given a user-access-token, and Brick API will trigger POST and GET method.

Function postResult()

This function happened after the user successfully signed in to a Financial Institution account, POST method is called by Brick API, and this function will retrieve the user-access-token, bankId, transactions details, accounts detail if the user login to Jenius Account and only user-access-token if the user login with other Financial Institution Account.

#Handle POST method from Brick API
@app.route("/result",methods=['POST'])
def postResult():
    #reset jenius dictionary
    jenius['jeniusTransactionDetail'] = []
    #collect the user-access-token that is available once user sign in the bank account
    data = request.json
    #temp to store the value
    temp = data["accessToken"]
    #condition for data retrieve from POST response is more than 2, then the user is using Jenius
    if(len(data) > 2):
        #condition for transaction not empty
        if(data['transactions'] is not None):
            #set boolean isJenius to true
            boolean['isJenius'] = True
            #populate jenius transaction to dictionary
            temp2 = json.loads(data['transactions'])
            jenius['jeniusTransactionDetail'] = temp2.copy()
        #condition for accounts not empty
        if(data['accounts'] is not None):
            #populate jenius account detail to dictionary
            temp3 = json.loads(data['accounts'])
            jenius['jeniusAccountDetail'] = temp3.copy()
    #randomize a sessionID
    session = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(20))
    #condition to check when accessToken is not found, then we will save user-access-token to ''
    if(temp == ''):
        #store the user-access-token into our dictionary
        dictionary["token"] = ''
        return "http://localhost:5000/result?sessionId="+session
    #condition when accessToken is found
    else:
        #store the user-access-token into our dictionary
        dictionary["token"] = temp
        #store sessionID to dictionary
        dictionary["session"] = session
        return "http://localhost:5000/result?sessionId="+session

Function getResult()

This function happened after user successfully signed in to a Financial Institution account, GET method is called by Brick API, and this function will pass all necessary value to end-point page.

#Handle GET method from Brick API
@app.route("/result",methods=['GET'])
def getResult():
    #when user-access-token is not found, we return error html
    if(dictionary["token"]==''):
        return render_template('Error.html')
    #when user-access-token is found, we return result/transaction page
    else:
        #call the 'Result.html' and pass transactions, account details, and date value
        return render_template('Result.html',dictionary=getTransaction(), userdetail = getUserDetail(), date=getDate())

Result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel = "stylesheet" href = "{{ url_for('static', filename='css/main.css') }}">
    <title>Transactions</title>
</head>
<body>
    <div class="container">
        <div class ="header">
            <div class ="personal-detail">
                <h2 class="title">Hello!</h2>
                {%if userdetail%}
                    <h2 class="title-account">
                        {{userdetail['accountNumber']}}
                    </h2>
                {%endif%}
                <h2 class="title-date">{{date}}</h2>
            </div>
        </div>
        <div class="balance">
            <h2>Balance</h2>
            <hr>
            {%if userdetail%}
                <div class="balance-wrapper">
                    <div class="available-balance">
                        <h2>RP {{userdetail['balances']['available']}}</h2>
                        <p style="text-align:center">Available Balance</p>
                    </div>
                    <div class="current-balance">
                        <h2>RP {{userdetail['balances']['current']}}</h2>
                        <p style="text-align:center">Current Balance</p>
                    </div>
                </div>
            {%endif%}
            <hr>
        </div>
        <div class="transaction">
            <h2>Transaction</h2>
            <hr>
            <table class="transaction">
                <div class="test" style="height:100%">
                    <tr>
                        <th class="time">Time</th>
                        <th class="description">Description</th>
                        <th class="status">Status</th>
                        <th class="amount">Amount</th>
                    </tr>
                    {%if dictionary%}
                        {%for i in range (0, dictionary['description']|length)%}
                        <tr>
                            <td>{{dictionary['date'][i]}}</td>
                            <td>{{dictionary['description'][i]}}</td>
                            <td>{{dictionary['status'][i]}}</td>
                            <td>Rp {{dictionary['amount'][i]}}</td>
                        </tr>
                        {%endfor%}
                    {%endif%}
                </div>
            </table>

        </div>
        <div class="footer"></div>
    </div>
    
    
</body>
</html>

Function getUserAccounts()

This function is called in function getUserDetail() and will retrieve all accounts from within the user's one Financial Institution.

def getUserAccounts():
    #userToken is the user-access-token that we can retrieve from dictionary
    userToken = dictionary['token']
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':'Bearer '+userToken}
    #retrieve the json value from the link
    request = Request(base_link+'account/list', headers=header)
    response = urlopen(request).read().decode('utf-8')
    data = json.loads(response)['data']
    #condition to store default value when the data in sandbox.onebrick.io/v1/account/list is empty (specifically for mockbank account)
    if(len(data) == 0):
        user_account['accountHolder'].append('Johndoe')
        user_account['accountNumber'].append('9870675789')
        user_account['accountId'].append('qwerty//++--==')
        user_account['balances']['available'] = "100,987"
        user_account['balances']['current'] = "100,987"
    #condition when the value is not empty
    else:
        for i in range (len(data)):
            #store all the information to user account information
            user_account['accountHolder'].append(data[i]['accountHolder'])
            user_account['accountNumber'].append(data[i]['accountNumber'])
            user_account['accountId'].append(data[i]['accountId'])
            user_account['balances']['available'] = "{:,}".format(data[i]['balances']['available'])
            user_account['balances']['current'] = "{:,}".format(data[i]['balances']['current'])
    return user_account #return the user_account dictionary

Example of Account List in JSON format that we retrieved

{
    "status": 200,
    "message": "OK",
    "data": [
        {
            "accountId": "UarXg4ad/81344wJF8xthY==",
            "accountHolder": "JOHN DOE",
            "accountNumber": "1551110757891",
            "balances": {
                "available":22130.0,
                "current": 22130.0
            }
        },
        {
            "accountId": "ZUTBeQcl2FTqNUwcVDuRFF==",
            "accountHolder": "JOHN DOE",
            "accountNumber": "1234567890123",
            "balances": {
                "available": 320554.15,
                "current": 320554.15
            }
        }
    ]
}

Function getUserDetail()

This function is called in function getResult() and will retrieve all Financial Institution accounts from the same Financial Institution.

def getUserDetail():
    #userToken to store the user-access-token
    userToken = dictionary['token']
    #accountId is to get which specific account that is being accessed
    accountId = getUserAccounts()['accountId'][0]
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':'Bearer '+userToken}
    #retrieve the json value from the link
    request = Request(base_link+'account/detail?accountId='+accountId, headers=header)
    response = urlopen(request).read().decode('utf-8')
    data = json.loads(response)['data']
    #store all the data from the json into user_detail dictionary
    user_detail['accountHolder']=data['accountHolder']
    user_detail['accountNumber']=data['accountNumber']
    user_detail['accountId']=data['accountId']
    user_detail['balances']['available'] = "{:,}".format(data['balances']['available'])
    user_detail['balances']['current'] = "{:,}".format(data['balances']['current'])
    return user_detail #return user_detail dictionary

Function getUserDetailJenius()

This function is called in function getResult() and will store the user's Jenius Bank Account detail.

def getUserDetailJenius():
    #reset user_detail value
    user_detail['accountHolder'] =""
    user_detail['accountNumber'] = ""
    user_detail['acccountId'] = ""
    user_detail['balances']['available'] =""
    user_detail['balances']['current'] =""
    #populate dictionary for transaction from response in POST method of Brick API
    for i in range(len(jenius['jeniusAccountDetail'])):
        user_detail['accountHolder']= jenius['jeniusAccountDetail'][i]['accountHolder']
        user_detail['accountNumber']= jenius['jeniusAccountDetail'][i]['accountNumber']
        user_detail['acccountId']= jenius['jeniusAccountDetail'][i]['accountId']
        user_detail['balances']['available']="{:,}".format(jenius['jeniusAccountDetail'][i]['balances']['available'])
        user_detail['balances']['current']="{:,}".format(jenius['jeniusAccountDetail'][i]['balances']['current'])
    return user_detail

Example of Account Details from one Account ID in JSON format that we retrieved

{
  "status": "status",
  "message": "message",
  "data": {
    "updateTimestamp": "2020-08-21T17:33:30",
    "accountId": "jwYhjuy4tQZx8sZj3oBrg9fSqvzsR41F",
    "accountHolder": "Jane Doe",
    "accountNumber": "1342006123456",
    "balances": {
      "available": "675000.00",
      "current": "675000.00"
    },
    "lastUpdated": "2020-08-31 14:27:37 +07:00",
    "lastUpdatedTransaction": "2020-08-31 13:08:05 +07:00"
  }
}

Function getTransaction()

This function is called in function getResult() and will retrieve all transactions from the user account.

def getTransaction():
    #clear the dictionary value so that everytime page is refreshed no information is duplicated
    dictionary['date'] =[]
    dictionary['description'] = []
    dictionary['status'] = []
    dictionary['amount']=[]
    userToken = dictionary['token']
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':'Bearer '+userToken}
    #retrieve the transactions in the api from given date
    #you can change the value of xxxx with date range you want
    #e.g https://sandbox.onebrick.io/v1/transaction/list?from=2020-01-25&to=2020-12-31
    request = Request(base_link+'transaction/list?from=YYYY-MM-DD&to=YYYY-MM-DD', headers=header)
    response = urlopen(request).read().decode('utf-8')
    data = json.loads(response)['data']
    #store the information of the transaction's date, description, status and amount into our dictionary
    for i in range (len(data)):
        dictionary['date'].append(data[i]['date'])
        dictionary['description'].append(data[i]['description'])
        dictionary['status'].append(data[i]['status'])
        dictionary['amount'].append("{:,}".format(data[i]['amount']))
    return dictionary #return dictionary

Function getTransactionJenius()

This function is called in function getResult() and will store all Jenius Bank transactions from the user account.

def getTransactionJenius():
    #reset dictionary value
    dictionary['date'] =[]
    dictionary['description'] = []
    dictionary['status'] = []
    dictionary['amount']=[]
    #populate dictionary for transaction from response in POST method of Brick API
    for i in range(len(jenius['jeniusTransactionDetail'])):
        dictionary['date'].append(jenius['jeniusTransactionDetail'][i]['date'])
        dictionary['description'].append(jenius['jeniusTransactionDetail'][i]['description'])
        dictionary['status'].append(jenius['jeniusTransactionDetail'][i]['status'])
        dictionary['amount'].append(jenius['jeniusTransactionDetail'][i]['amount'])
    return dictionary

Example of Transaction in JSON format that we retrieved

{
    "status": 200,
    "message": "OK",
    "data": [
        {
            "id": 9744,
            "account_id": "jwYhjuy4tQZx8sZj3oBrg9fSqvzsR41F==",
            "category_id": 24,
            "subcategory_id": 141,
            "merchant_id": 8,
            "location_country_id": 0,
            "location_city_id": 0,
            "outlet_outlet_id": 0,
            "amount": 600000.0,
            "date": "2020-06-29",
            "description": "ATM-MP SA CWD XMD S1AW1MJK /7774759936/ATM-RCOASIAAFRK 4616993200225278 RCOASIAAFRK",
            "status": "CONFIRMED",
            "direction": "out"
        },
        {
            "id": 9743,
            "account_id": "jwYhjuy4tQZx8sZj3oBrg9fSqvzsR41F==",
            "category_id": 22,
            "subcategory_id": 129,
            "merchant_id": 0,
            "location_country_id": 0,
            "location_city_id": 0,
            "outlet_outlet_id": 0,
            "amount": 1000.0,
            "date": "2020-06-29",
            "description": "CA/SA UBP DR/CR-ATM UBP60116073701FFFFFF085755130021 50000 S1AW1MJK /7774759939/ATM-RCOASIAAFRK P085755130021",
            "status": "CONFIRMED",
            "direction": "out"
        }
     ]
}

Function getDate()

This function is called in function getResult() and will get the current date this program is running.

def getDate():
    date= datetime.today().strftime('%d %B %Y')
    return date #return current date

main.py

Your final code should look like the following.

#Import Flask is to use Flask API
#Import render_template is to render a template HTML in your python file
#Import redirect for redirecting program to use onebrick sandbox api
#Import request in flask library to get json value from post redirect in demo sandbox
from flask import Flask, render_template,redirect,request
#Import Request is to access a link to retrieve the json value
#Import urlopen is to access the url object that is retrieved from  Request
#Import base64 is to encode and decode
from urllib.request import Request, urlopen,base64
#Import CORS to enable all of HTTP headers mechanism
from flask_cors import CORS, cross_origin
#read json format
import json
#Import random and string for generating session
import random,string
#Import datetime to get current date
from datetime import datetime

#Flask app configuration
app = Flask(__name__)
#CORS configuration for any header to be accessed in HTTP
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

#dictionary dict to store the contents of transaction details
dictionary= {
    "session":"",
    "token" :"",
    "date":[],
    "description":[],
    "status":[],
    "amount":[],
}

#user_account dict to store the user's accounts detail in sandbox.onebrick.io/account/list
user_account= {
    "accountHolder":[],
    "accountNumber" :[],
    "accountId":[],
    "balances":{
        "available":"",
        "current":"",
    }
}

#user_detail dict to store the specific user's account detail
user_detail= {
    "accountHolder":"",
    "accountNumber" :"",
    "accountId":"",
    "balances":{
        "available":"",
        "current":"",
    }
}

#boolean if user uses Jenius Bank
boolean = {
    "isJenius" : False
 }

#jenius dictionary to store jenius transaction and account details
jenius = {
    "jeniusTransactionDetail":[],
    "jeniusAccountDetail":[]
}
#base link
base_link = "https://sandbox.onebrick.io/v1/"

#first function to run when python file is executed
@app.route("/")
def main():
    return render_template('Start.html')

#trigger functionn when form is posted in 'Start.html'
@app.route("/goto",methods=['POST'])
def goto():
    #call function authentication() to get the JWT-public-access-token
    token = authentication()
    #url to access onebrick.io API
    url = base_link+"index?"+"accessToken="+token+"&redirect_url="+"http://localhost:5000/result"
    return redirect(url)

#trigger the function when moneysave demo do method post
@app.route("/result",methods=['POST'])
def postResult():
    #reset jenius dictionary
    jenius['jeniusTransactionDetail'] = []
    #collect the user-access-token that is available once user sign in the bank account
    data = request.json
    #temp to store the value
    temp = data["accessToken"]
    #condition for data retrieve from POST response is more than 2, then the user is using Jenius
    if(len(data) > 2):
        #condition for transaction not empty
        if(data['transactions'] is not None):
            #set boolean isJenius to true
            boolean['isJenius'] = True
            #populate jenius transaction to dictionary
            temp2 = json.loads(data['transactions'])
            jenius['jeniusTransactionDetail'] = temp2.copy()
        #condition for accounts not empty
        if(data['accounts'] is not None):
            #populate jenius account detail to dictionary
            temp3 = json.loads(data['accounts'])
            jenius['jeniusAccountDetail'] = temp3.copy()
    #randomize a sessionID
    session = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(20))
    #condition to check when accessToken is not found, then we will save user-access-token to ''
    if(temp == ''):
        #store the user-access-token into our dictionary
        dictionary["token"] = ''
        return "http://localhost:5000/result?sessionId="+session
    #condition when accessToken is found
    else:
        #store the user-access-token into our dictionary
        dictionary["token"] = temp
        #store sessionID to dictionary
        dictionary["session"] = session
        return "http://localhost:5000/result?sessionId="+session

#trigger function when moneysave demo do method get
@app.route("/result",methods=['GET'])
def getResult():
    #when user-access-token is not found, we return error html
    if(dictionary["token"]==''):
        return render_template('Error.html')
    #when user-access-token is found, we return result/transaction page
    else:
        #condition to check if user is using Jenius Bank
        if(boolean['isJenius'] == False):
            return render_template('Result.html',dictionary=getTransaction(), userdetail = getUserDetail(), date=getDate())
        else:
            return render_template('Result.html',dictionary=getTransactionJenius(), userdetail = getUserDetailJenius() ,date=getDate())

#function to get the JWT-public-access-token
def authentication():
    #change the value XXXXX to your client ID in Brick account
    clientID = "XXXXX"
    #change the value XXXXX to your client Secret in Brick account
    clientSecret = "XXXXX"
    account = clientID +":" +clientSecret
    #perform base 64 encoding for basic authentication
    authorize = "Basic " + base64.b64encode(account.encode()).decode()
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':authorize}
    #retrieve the json value from the link
    request = Request(base_link+'auth/token', headers=header)
    response = urlopen(request).read().decode('utf-8') 
    data = json.loads(response)['data']
    return data['access_token'] 

#function to get all the transaction in a user's account
def getTransaction():
    #clear the dictionary value so that everytime page is refreshed no information is duplicated
    dictionary['date'] =[]
    dictionary['description'] = []
    dictionary['status'] = []
    dictionary['amount']=[]
    userToken = dictionary['token']
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':'Bearer '+userToken}
    #retrieve the json value from the link
    #change the date range to your choice
    request = Request(base_link+'transaction/list?from=YYYY-MM-DD&to=YYYY-MM-DD', headers=header)
    response = urlopen(request).read().decode('utf-8')
    data = json.loads(response)['data']
    #store the information of the transaction's date, description, status and amount into our dictionary
    for i in range (len(data)):
        dictionary['date'].append(data[i]['date'])
        dictionary['description'].append(data[i]['description'])
        dictionary['status'].append(data[i]['status'])
        dictionary['amount'].append("{:,}".format(float(data[i]['amount'])))
    return dictionary

def getTransactionJenius():
    #reset dictionary value
    dictionary['date'] =[]
    dictionary['description'] = []
    dictionary['status'] = []
    dictionary['amount']=[]
    #populate dictionary for transaction from response in POST method of Brick API
    for i in range(len(jenius['jeniusTransactionDetail'])):
        dictionary['date'].append(jenius['jeniusTransactionDetail'][i]['date'])
        dictionary['description'].append(jenius['jeniusTransactionDetail'][i]['description'])
        dictionary['status'].append(jenius['jeniusTransactionDetail'][i]['status'])
        dictionary['amount'].append(jenius['jeniusTransactionDetail'][i]['amount'])
    return dictionary

#function to retrieve all user's account in 1 user-access-token (in the same bank)
def getUserAccounts():
    #userToken is the user-access-token that we get from dictionary
    userToken = dictionary['token']
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':'Bearer '+userToken}
    #retrieve the json value from the link
    request = Request(base_link+'account/list', headers=header)
    response = urlopen(request).read().decode('utf-8')
    data = json.loads(response)['data']
    #condition to store default value when the data in sandbox.onebrick.io/v1/account/list is empty (specifically for mockbank account)
    if(len(data) == 0):
        user_account['accountHolder'].append('Johndoe')
        user_account['accountNumber'].append('9870675789')
        user_account['accountId'].append('qwerty//++--==')
        user_account['balances']['available'] = "100,987"
        user_account['balances']['current'] = "100,987"
    #condition when the value is not empty
    else:
        for i in range (len(data)):
            #store all the information to user account information
            user_account['accountHolder'].append(data[i]['accountHolder'])
            user_account['accountNumber'].append(data[i]['accountNumber'])
            user_account['accountId'].append(data[i]['accountId'])
            user_account['balances']['available'] = "{:,}".format(data[i]['balances']['available'])
            user_account['balances']['current'] = "{:,}".format(data[i]['balances']['current'])
    return user_account

#function to  get the user account detail from 1 account ID
def getUserDetail():
    #userToken to store the user-access-token
    userToken = dictionary['token']
    #accountId is to get which specific account that is being accessed
    accountId = getUserAccounts()['accountId'][0]
    #initialize header to access the url
    header = {
        'Content-type':'application/json',
        'Authorization':'Bearer '+userToken}
    #retrieve the json value from the link
    request = Request(base_link+'account/detail?accountId='+accountId, headers=header)
    response = urlopen(request).read().decode('utf-8')
    data = json.loads(response)['data']
    #store all the data from the json into user_detail dictionary
    user_detail['accountHolder']=data['accountHolder']
    user_detail['accountNumber']=data['accountNumber']
    user_detail['accountId']=data['accountId']
    user_detail['balances']['available'] = "{:,}".format(data['balances']['available'])
    user_detail['balances']['current'] = "{:,}".format(data['balances']['current'])
    return user_detail

def getUserDetailJenius():
    #reset user_detail value
    user_detail['accountHolder'] =""
    user_detail['accountNumber'] = ""
    user_detail['acccountId'] = ""
    user_detail['balances']['available'] =""
    user_detail['balances']['current'] =""
    #populate dictionary for transaction from response in POST method of Brick API
    for i in range(len(jenius['jeniusAccountDetail'])):
        user_detail['accountHolder']= jenius['jeniusAccountDetail'][i]['accountHolder']
        user_detail['accountNumber']= jenius['jeniusAccountDetail'][i]['accountNumber']
        user_detail['acccountId']= jenius['jeniusAccountDetail'][i]['accountId']
        user_detail['balances']['available']="{:,}".format(jenius['jeniusAccountDetail'][i]['balances']['available'])
        user_detail['balances']['current']="{:,}".format(jenius['jeniusAccountDetail'][i]['balances']['current'])
    return user_detail

#function to get the current date when the program is running
def getDate():
    date= datetime.today().strftime('%d %B %Y')
    return date

# def checkJenius():
#     print("this happend")
#debugging purpose
if __name__ == "__main__":
    app.run(debug = True)

Did this page help you?