Flask Dashboard Argon - adding a secure RESTfull node 
Tags: flask, dashboard, appseed
Published: 2019-06-18 10:34:08

---
title: Flask Dashboard Argon - adding a secure RESTfull node 
published: true
description: Learn Flask by coding a secure RESTfull node on top of Argon Dashboard design  
cover_image: https://raw.githubusercontent.com/app-generator/static/master/flask-argon-dashboard-tutorial/flask-dashboard-adding-rest-cover.jpg
tags: flask, dashboard, appseed
---

Hello Coders, 

This article aims to help less experienced programmers to code a secure RESTfull node using **Flask-RESTfull** on top of an existing **Flask dashboard** application.

> *Thanks for reading!* - Content provided by **[App Generator](https://appseed.us/)**.

---

![Flask Dashboard Argon - Adding RESTfull node.](https://raw.githubusercontent.com/app-generator/static/master/flask-argon-dashboard-tutorial/flask-dashboard-adding-rest-intro.gif) 

> Topics like adding a database, authentication, and basic setup of a Flask application are explained in the other two articles: [Learn Flask by coding](https://dev.to/sm0ke/flask-learn-by-coding-1o8o) and [Adding a database to Flask](https://dev.to/sm0ke/argon-dashboard-learn-flask-by-coding-2b27).    

## App Features
 
 - [Open-Source](https://github.com/app-generator/flask-argon-dashboard), MIT license
 - Live [DEMO](https://flask-argon-dashboard.appseed.us/)
 - Backend - [Flask](http://flask.pocoo.org/) 
 - RESTnode coded in [Flask-RESTful](https://flask-restful.readthedocs.io/en/latest/), protected by authentication  
 - Database - [SQLite](https://www.sqlite.org/index.html)
 - ORM - SQLAlchemy     

## Implementation steps

In order to connect the Dashboard to real data, we need to implement three items:
- A new table that holds the charts information, 
- The REST API node, to serve data,
- A consumer (client), responsible to read the information from the REST service and update the charts. Let's code!
 

### Adding a new table

The Stats table has a simple structure built with key/value pattern. The key, identify the information and can store integers in `val` field or strings in `val_s`.   
 
```
class Stats(db.Model):

    id    = db.Column(db.Integer,     primary_key=True)
    key   = db.Column(db.String(64),  unique=True)
    val   = db.Column(db.Integer)
    val_s = db.Column(db.String(256))
``` 

To create the new table and query the content we can use the Flask shell

```
$ flask shell
$ >>> 
$ >>> from app import db
$ >>> db.create_all()
$ >>>  
$ >>> from app.models import Stats
$ >>> Stats.query.all() 
[]
```

Let's add a new row, on the table, to be later used by the dashboard

```
$ flask shell
$ >>> 
$ >>> from app.models import Stats
$ >>> traffic = Stats('traffic') # create a new counter 
$ >>> 
$ >>> traffic.val = 10 # set the value
$ >>> traffic.save() # save the new value in database 
$ >>> 
$ >>> Stats.query.all() 
[<Stats traffic / 10 /  >]
```
As we can see, the latest query shows one counter defined, with value 10. At this point we have data in our database, let's build the REST point to release it into the wild.

### The REST API node 

Flask offers many REST libraries, Flask-RESTful is just one of them. [Flask-RESTPlus](https://flask-restplus.readthedocs.io/en/stable/) also looks very promising. Now back to our REST point, the relevant changes are:

> ApiStats class that handles the stats requests - [the source](https://github.com/app-generator/flask-argon-dashboard/blob/master/app/restapi/stats.py). The endpoint will serve information only for authenticated users, and return a 401 (not authorized) response otherwise.

```
from flask_restful import Resource
from flask_login   import current_user

from app.models    import Stats

class ApiStats(Resource):

    def get(self,segment):

        if not current_user.is_authenticated:
            return {'err': 'auth'}, 401

        # See the model for details 
        val = Stats( segment ).val 

        if 'traffic' == segment:
            return { segment : val }, 200
```


### Activate the endpoint

The ApiStats class, built on top of Flask-RESTful must be added in the core of the application, during the init phase. If we look at the [source of __init.py](https://github.com/app-generator/flask-argon-dashboard/blob/master/app/__init__.py) file, our app constructor, we can easily spot the relevant lines: 

```
from flask import Flask
from flask_restful import Api # <-- import the RESTfull magic

app = Flask(__name__)
api = Api(app) #  bind the RESTfull library to our application

# Define the routes resolved by the REST API
api.add_resource(ApiStats, '/api/stats/<string:segment>')
```

The API can be tested directly in the browser by accessing `http://localhost:5000/api/stats/traffic` 

![Flask Dashboard Argon - RESTfull smoke test.](https://raw.githubusercontent.com/app-generator/static/master/flask-argon-dashboard-tutorial/flask-dashboard-argon-rest-browser-test.jpg) 


At this point, we have the information saved in the database, the RESTfull endpoint published, all we need is the consumer to inject the information collected from the REST API into the dashboards. 

### Update the dashboard with RESTfull data

Inject the information can be done with a simple jQuery call via `$.getJson()` helper. The API consumer code is saved into [app.js](https://github.com/app-generator/flask-argon-dashboard/blob/master/app/static/assets/js/app.js) Javascript file:

```
'use strict';

$(function() {
    
    // Update the Traffic cell
    $.getJSON('/api/stats/traffic', function( data ) { 
        //console.log( ' -> ' + data['traffic'] ) 
        $('#stats_traffic').html( data['traffic'] );
    });

});
``` 
This simple API consumer, request the information from the API endpoint and inject the value in the dashboard. Let's visualize the dashboard:

- User is not authenticated

![Flask Dashboard Argon - User not Auth](https://raw.githubusercontent.com/app-generator/static/master/flask-argon-dashboard-tutorial/flask-dashboard-argon-rest-not-authorized.jpg)
 
- User is authenticated

![Flask Dashboard Argon - User Authorized](https://raw.githubusercontent.com/app-generator/static/master/flask-argon-dashboard-tutorial/flask-dashboard-argon-rest-authorized.jpg)

If we update the value of the traffic counter in the database and refresh the page, the new value will be displayed in the traffic card. 


> **Thank you!** 

## Resources

 - [Flask Dashboard Argon](https://appseed.us/admin-dashboards/flask-dashboard-argon) - app info
 - [Admin Dashboards](https://appseed.us/admin-dashboards) - index provided by AppSeed 
 - Curated list of [Admin Dashboards](https://admin-dashboards.com/) - open-source project with apps submitted by developers