Python Flask Web Application Tutorial 2020: Display Coinmarketcap API Data

Python Flask Web Application Tutorial 2020: Display Coinmarketcap API Data

In this tutorial, we are going to build a python flask web application from scratch – that will display coinmarketcap data for the top 10 coins.

You can use the principles learned from this web application to build similar apps that get data from a real-time hosted API. But before we get started – we discuss the difference between a website and a web-application.

Difference between a website and a web-application

In this article linked here – we discussed in great detail the main difference between a website an a web-application. A web-application generally involves a website that displays dynamic content. A facebook page is a good example – every user sees a different website based on their profile. A web application as a result requires the following main components:

  1. A front end website (where this information will be displayed to the user)
  2. A back-end database where the information is stored
  3. A server that does some computations and delivers the data or information to the front end client.

This back-end database can be any source of data – such as an API or another website. In this tutorial – our data source will be the coinmarketcap API.

python flask web application
python flask web application

A website on the other hand displays dynamic content. This blog is a good example, it is written once and the content never changes. Everyone who comes to this url will see the same content.

Python Flask Web Application

There are many frameworks that are used to develop web applications, we are going to show you how to do it quickly with python and flask.

Read the documentation here – https://flask.palletsprojects.com/en/1.1.x/

Install Python, Python PIP and Set-up tools

Depending on which operating system you are working with – install python to get started on their official website there is a download link:

https://www.python.org/downloads/

install python
install python

Build Working directory

The standard python flask web application working directory looks like this

Root
|______STATIC
|        |________CSS
|        |________Fonts
|        |________Images
|        |________JS
|
|______TEMPLATES
|           |________index.html
|           |________404.html
|
|
|____ app.py
|____ config.py

However, we are building a simplified application and will not have a static folder and config file. Our working directory will look like:

Root
|
|
|____TEMPLATES
|        |______index.html
|
|____ app.py
|____ api.py

We are going to use just one html file called index.html. We will need two python documents: (1) app.py will be used for the flask app and (2) api.py will be the used to make the api calls to get data that will be sent to the app.py file.

File Contents api.py

This is the file that will contain all the functions related to getting the data from the API. we will need the requests python library for this.

You will also need to create an account with coinmarket cap and get an API key that you will use in this file.

Register an account with Coinmarket cap here: https://coinmarketcap.com/api/pricing/

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json


class Crypto:

    def get_top_5(self):

        url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
        parameters = {
          'start':'1',
          'limit':'5',
          'convert':'USD'
        }
        headers = {
          'Accepts': 'application/json',
          'X-CMC_PRO_API_KEY': 'enter-your-api-key-here',
        }

        session = Session()
        session.headers.update(headers)

        response = session.get(url, params=parameters)
        data = json.loads(response.text)
        return data['data']

    def get_top_10(self):

        url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
        parameters = {
          'start':'1',
          'limit':'10',
          'convert':'USD'
        }
        headers = {
          'Accepts': 'application/json',
          'X-CMC_PRO_API_KEY': 'enter-your-api-key-here',
        }

        session = Session()
        session.headers.update(headers)

        response = session.get(url, params=parameters)
        data = json.loads(response.text)
        return data['data']

File Contents app.py

This is the file where we will create our flask application.

from api import Crypto
from flask import Flask, render_template

app = Flask(__name__)

crypto  = Crypto()

@app.route("/")
def hello():
    results = crypto.get_top_10()

    for result in results:
        result['quote']['USD']['price'] = '$ ' + "{:.2f}".format(result['quote']['USD']['price'])

    return render_template('index.html', **locals())

if __name__ == "__main__":
    app.run(host='0.0.0.0')

In this file we import both flask and the api file we just created. We are using render_template to render the html file, which must be saved in the templates folder.

File Contents index.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin=">
    <title>Hello, world!</title>
  </head>
  <body>
    <div class="container">
      <br>
      <br>
      <br>
      <br>
      <h1>Skolo Online Crypto Tracker</h1>
      <h3>Displaying the latest Crypto prices from CoinmarketCap API</h3>

      <table class="table">
         <thead class="thead-dark">
           <tr>
             <th scope="col">Cryto Name</th>
             <th scope="col">Symbol</th>
             <th scope="col">Slug</th>
             <th scope="col">Price</th>
           </tr>
         </thead>


         <tbody>

           {% for obj in results %}
           <tr>
             <td>{{obj.name}}</td>
             <td>{{obj.symbol}}</td>
             <td>{{obj.slug}}</td>
             <td>{{obj.quote.USD.price}}</td>
           </tr>
           {% endfor %}

         </tbody>
        </table>
    </div>


    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous">>

    <!-- Option 2: jQuery, Popper.js, and Bootstrap JS
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></scrip>
    -->
  </body>
</html>

In this index file, we are simply using a table to display the results we get from the API call. We also install bootsrap JS and CSS library to style our website.

Install Libraries and run

To install the required python libraries you need to run:

pip install requests
pip install flask

To run the program

python app.py

There you go – you will be able to see the top 10 crypto data. Note that the API returns a lot of information that you can display as you wish, simply parse the JSON object returned as you wish.

Get the full tutorial video

Leave a Reply

Your email address will not be published.

Subscribe to our mailing list

And get this 💃💃 Free😀 eBook !

Holler Box