Create a Real-Time Cricbuzz Application using Flask and RapidAPI

Create a Real-Time Cricbuzz Application using Flask and RapidAPI

Real-Time Cricbuzz Application using Flask and RapidAPI

Prerequisites for the Application:

  • Rapid API Account

  • Python3 installed

  • Flask Installed

  • Basic Python Knowledge

MUST CLONE THE REPO

Create a Rapid API Account

Sign Up for the Rapid API Account.

Search for the required API for getting the Cricbuzz API

Search ==> "Cricbuzz Cricket"

On the Endpoints Tab ==> Click on the Subscribe ==> Click on the free plan 0$ ==> In this API we do not need to fill in the credit card details

NOTE: Some Free APIs also need to fill in the details of the Credit Card so keep an eye on that too.

Click on the button "Test Endpoint"

In the code snippet tab take a look at the URL and the Headers section this will be an important part of the integration of our Application and the API so we need to keep it safe. (We will add it in a file in our code)

Create a folder "Cricbuzz-App" in your local machine ==> Add file test.py

Test.py will look like this

requests => Is a popular HTTP request library; that simplifies the process of sending HTTP requests and handling responses. (Widely used to manage API requests)

import requests
#Both the URL and headers are copied from your RAPID API Dashboard 
url = "https://cricbuzz-cricket.p.rapidapi.com/matches/v1/recent"

headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "YOUR_RAPID_API_KEY"  # Replace with your RapidAPI key
    }
requests.get(url, headers=headers)

Now let us check if our requests are getting resolved via the API or not using the requests.get(URL, headers=headers) we are etching the URL and the headers and we can store it into a variable named a response (standard procedure)

response = requests.get(url, headers=headers)
print(response)
# To format the output in the Json format we use it as the following
print(response.json())

What we are expecting from our application to perform

  • To show recent matches

  • To show upcoming matches

Logic for showing the recent matches

For that, we are going to need to fetch the data from our API

For getting matches we are storing the above evaluated response.json in the data variable and we will further traverse the dictionary to get the list of matches

data = response.json()
matches = data['typeMatches']['0']['seriesMatches'][0]['seriesAdWrapper']['matches']

The output will be like so we need to traverse it.

traversing in the loop we will use it like

We are using the table and appending the library;

from tabulate import tabulate

Also, we need it to append to the details

Using f-string to append the strings in our desired format

Initialize the table (keep it unallocated for now)

table = []

Getting the match description (We need to traverse through the Dictionary)

 table.append(["Match Description", f"{match['matchInfo']['matchDesc']} , {match['matchInfo']['team1']['teamName']} vs {match['matchInfo']['team2']['teamName']}"])

Series Name will be extracted as below and use the append series name which we will get inside the match info

table.append(["Series Name", match['matchInfo']['seriesName']])

Match Format will get it as

table.append(["Match Format", match['matchInfo']['matchFormat']])

Result

table.append(["Result", match['matchInfo']['status']])

We will get the details about both the team's details

        table.append([f"{match['matchInfo']['team1']['teamName']}", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"])
        table.append([f"{match['matchInfo']['team2']['teamName']}", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"])

To add the headers to the table we are using it and showing in the grid format, printing the result

headers = ["Key", "Value"]
print(tabulate(table, headers=headers, tablefmt="grid"))
print("\n")

The Output will look something in this format.

In conclusion, our file will look like the

     for match in matches:
        table = []
        table.append(["Match Description", f"{match['matchInfo']['matchDesc']} , {match['matchInfo']['team1']['teamName']} vs {match['matchInfo']['team2']['teamName']}"])
        table.append(["Match Details", ""])
        table.append(["Series Name", match['matchInfo']['seriesName']])
        table.append(["Match Format", match['matchInfo']['matchFormat']])
        table.append(["Result", match['matchInfo']['status']])
        table.append([f"{match['matchInfo']['team1']['teamName']}", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"])
        table.append([f"{match['matchInfo']['team2']['teamName']}", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"])

        headers = ["Key", "Value"]
        print(tabulate(table, headers=headers, tablefmt="grid"))
        print("\n")

We will add it into a function to reuse it in test.py

import requests
from tabulate import tabulate

def fetch_cricket_scores():
    url = "https://cricbuzz-cricket.p.rapidapi.com/matches/v1/recent"

    headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "RAPID_API_KEY"  # Replace with your RapidAPI key
    }
    response = requests.get(url, headers=headers)
    data = response.json()

    matches = data['typeMatches'][0]['seriesMatches'][0]['seriesAdWrapper']['matches']
    for match in matches:
        table = []
        table.append(["Match Description", f"{match['matchInfo']['matchDesc']} , {match['matchInfo']['team1']['teamName']} vs {match['matchInfo']['team2']['teamName']}"])
        table.append(["Match Details", ""])
        table.append(["Series Name", match['matchInfo']['seriesName']])
        table.append(["Match Format", match['matchInfo']['matchFormat']])
        table.append(["Result", match['matchInfo']['status']])
        table.append([f"{match['matchInfo']['team1']['teamName']}", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"])
        table.append([f"{match['matchInfo']['team2']['teamName']}", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"])

        headers = ["Key", "Value"]
        print(tabulate(table, headers=headers, tablefmt="grid"))
        print("\n")
        print(match)

fetch_cricket_scores()

Make a requirement.txt file

flask
tabulate

Run the requirement.txt file

pip install -r requirements.txt

Now to add up the logic to fetch the upcoming matches we have the following.

We will create the new file as app.py

Add the logic prepared for the fetch of live scores

from flask import Flask, render_template
import requests
import json
from tabulate import tabulate
import os 

app = Flask(__name__)

def fetch_live_score():
  url = "https://cricbuzz-cricket.p.rapidapi.com/matches/v1/recent"
  headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key
    }
  response = requests.get(url, headers=headers)
  data = response.json() 
  matches_data = [] # we have kept a empty list

Now we need to traverse the list of live matches as we have figured logic earlier

for match in data['typeMatches'][0]['seriesMatches'][0]['seriesAdWrapper']['matches']:
    table = [
      [f"{match['matchInfo']['matchDesc']}, {match['matchInfo']['team1']['teamName']} VS {match['matchInfo']['team2']['teamName']}"],
      ["Series Name", match['matchInfo']['seriesName']],
      ["Match Format", match['matchInfo']['matchFormat']],
      ["Result", match['matchInfo']['status']],
      [f"{match['matchInfo']['team1']['teamName']} Score", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"],
      [f"{match['matchInfo']['team2']['teamName']} Score", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"]
    ]

We getting all the details added like Series Name, Match Format, Result, etc. Further to get the table data in the HTML format

    matches_data.append(tabulate(table, tablefmt="html"))
return matches_data
from flask import Flask, render_template
import requests
import json
from tabulate import tabulate
import os 

app = Flask(__name__)

def fetch_live_score():
  url = "https://cricbuzz-cricket.p.rapidapi.com/matches/v1/recent"
  headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key
    }
  response = requests.get(url, headers=headers)
  data = response.json() 
  matches_data = []

  for match in data['typeMatches'][0]['seriesMatches'][0]['seriesAdWrapper']['matches']:
    #print(match)
    table = [
      [f"{match['matchInfo']['matchDesc']}, {match['matchInfo']['team1']['teamName']} VS {match['matchInfo']['team2']['teamName']}"],
      ["Series Name", match['matchInfo']['seriesName']],
      ["Match Format", match['matchInfo']['matchFormat']],
      ["Result", match['matchInfo']['status']],
      [f"{match['matchInfo']['team1']['teamName']} Score", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"],
      [f"{match['matchInfo']['team2']['teamName']} Score", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"]
    ]
    matches_data.append(tabulate(table, tablefmt="html"))
    #print(matches_data)
  return matches_data  
#fetch_live_score()

To get the upcoming match data

def fetch_upcoming_matches():
    url = "https://cricbuzz-cricket.p.rapidapi.com/schedule/v1/international"
    headers = {
      "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
      "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key
    }
    response = requests.get(url, headers=headers)
    upcoming_matches = []

Check if the response is given back properly or not

if response.status_code == 200:
else:
    print("Failed to fetch cricket scores. Status code:", response.status_code)
return upcoming_matches

Add the code in try and except block

try:
    print("In Try Block")
except json.JSONDecodeError as e:
    print("Error parsing JSON:", e)
except KeyError as e:
    print("Key Error:", e)

We will have to traverse the schedule in match_schedules.

for schedule in match_schedules:

It will give us the dictionary 'scheduleAdWrapper' in the schedule; if it is available if not send a message that no match is scheduled

for schedule in match_schedules:
    if 'scheduleAdWrapper' in schedule:
        <YOUR LOGIC>
    else:
        print("No match scheduled for this entry")

We will get the consolidated logic as

try:
   data = response.json()
   match_schedules = data.get('matchScheduleMap', [])
   for schedule in match_schedules:
        if 'scheduleAdWrapper' in schedule:
            <YOUR LOGIC>
        else:
            print("No match scheduled for this entry")
except json.JSONDecodeError as e:
    print("Error parsing JSON:", e)
except KeyError as e:
    print("Key Error:", e)

The logic for Scheduled Matches like getting the dates and matches from the Dictionary

date = schedule['scheduleAdWrapper']['date']
matches = schedule['scheduleAdWrapper']['matchScheduleList']

We will also traverse the matches to get the match info

for match_info in matches:
    for match in match_info['matchInfo']:

Get the description and match data from team1 and team2 and append it to the upcoming_matches.append()

for match_info in matches:
    for match in match_info['matchInfo']:
        description = match['matchDesc']
        team1 = match['team1']['teamName']
        team2 = match['team2']['teamName']
        match_data = {
           'Date': date,
           'Description': description,
           'Teams': f"{team1} vs {team2}"
        }
        upcoming_matches.append(match_data)
for schedule in match_schedules:
    if 'scheduleAdWrapper' in schedule:
       date = schedule['scheduleAdWrapper']['date']
       matches = schedule['scheduleAdWrapper']['matchScheduleList']

        for match_info in matches:
            for match in match_info['matchInfo']:
                description = match['matchDesc']
                team1 = match['team1']['teamName']
                team2 = match['team2']['teamName']
                match_data = {
                    'Date': date,
                    'Description': description,
                    'Teams': f"{team1} vs {team2}"
                 }
                upcoming_matches.append(match_data)

     else:
           print("No match scheduled for this entry")

The whole logic will look as follows fetch_upcoming_matches():

def fetch_live_score():
  url = "https://cricbuzz-cricket.p.rapidapi.com/matches/v1/recent"
  headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key
    }
  response = requests.get(url, headers=headers)
  data = response.json() 
  matches_data = []

  for match in data['typeMatches'][0]['seriesMatches'][0]['seriesAdWrapper']['matches']:
    #print(match)
    table = [
      [f"{match['matchInfo']['matchDesc']}, {match['matchInfo']['team1']['teamName']} VS {match['matchInfo']['team2']['teamName']}"],
      ["Series Name", match['matchInfo']['seriesName']],
      ["Match Format", match['matchInfo']['matchFormat']],
      ["Result", match['matchInfo']['status']],
      [f"{match['matchInfo']['team1']['teamName']} Score", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"],
      [f"{match['matchInfo']['team2']['teamName']} Score", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"]
    ]
    matches_data.append(tabulate(table, tablefmt="html"))
    #print(matches_data)
  return matches_data  
#fetch_live_score()    


def fetch_upcoming_matches():
    url = "https://cricbuzz-cricket.p.rapidapi.com/schedule/v1/international"

    headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key

      }
    #
    response = requests.get(url, headers=headers)
    upcoming_matches = []

    if response.status_code == 200:
        try:
            data = response.json()
            match_schedules = data.get('matchScheduleMap', [])

            for schedule in match_schedules:
                if 'scheduleAdWrapper' in schedule:
                    date = schedule['scheduleAdWrapper']['date']
                    matches = schedule['scheduleAdWrapper']['matchScheduleList']

                    for match_info in matches:
                        for match in match_info['matchInfo']:
                            description = match['matchDesc']
                            team1 = match['team1']['teamName']
                            team2 = match['team2']['teamName']
                            match_data = {
                                'Date': date,
                                'Description': description,
                                'Teams': f"{team1} vs {team2}"
                            }
                            upcoming_matches.append(match_data)
                else:
                    print("No match schedule found for this entry.")

        except json.JSONDecodeError as e:
            print("Error parsing JSON:", e)
        except KeyError as e:
            print("Key error:", e)
    else:
        print("Failed to fetch cricket scores. Status code:", response.status_code)

    return upcoming_matches

Also to figure out the routing in the Flask

Routing at the root and using the render_templatye of the flask to render it in the index.html also passing the HTML page the cricket_scores and upcoming_matches details.

@app.route("/")
cricket_scores = fetch_live_score()
upcoming_matches = fetch_upcoming_matches()
return render_template('index.html', cricket_scores=cricket_scores, upcoming_matches=upcoming_matches)

Here we have the main runner function and we will run it on the localhost (127.0.0.1) and on the PORT 8080; with the debug mode as True.

if __name__ == "__main__":
  app.run(port=int(os.environ.get("PORT", 8080)), host='0.0.0.0', debug=True)
from flask import Flask, render_template
import requests
import json
from tabulate import tabulate
import os 

app = Flask(__name__)

def fetch_live_score():
  url = "https://cricbuzz-cricket.p.rapidapi.com/matches/v1/recent"
  headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key
    }
  response = requests.get(url, headers=headers)
  data = response.json() 
  matches_data = []

  for match in data['typeMatches'][0]['seriesMatches'][0]['seriesAdWrapper']['matches']:
    #print(match)
    table = [
      [f"{match['matchInfo']['matchDesc']}, {match['matchInfo']['team1']['teamName']} VS {match['matchInfo']['team2']['teamName']}"],
      ["Series Name", match['matchInfo']['seriesName']],
      ["Match Format", match['matchInfo']['matchFormat']],
      ["Result", match['matchInfo']['status']],
      [f"{match['matchInfo']['team1']['teamName']} Score", f"{match['matchScore']['team1Score']['inngs1']['runs']}/{match['matchScore']['team1Score']['inngs1']['wickets']} in {match['matchScore']['team1Score']['inngs1']['overs']} overs"],
      [f"{match['matchInfo']['team2']['teamName']} Score", f"{match['matchScore']['team2Score']['inngs1']['runs']}/{match['matchScore']['team2Score']['inngs1']['wickets']} in {match['matchScore']['team2Score']['inngs1']['overs']} overs"]
    ]
    matches_data.append(tabulate(table, tablefmt="html"))
    #print(matches_data)
  return matches_data  
#fetch_live_score()    

def fetch_upcoming_matches():
    url = "https://cricbuzz-cricket.p.rapidapi.com/schedule/v1/international"

    headers = {
        "X-RapidAPI-Host": "cricbuzz-cricket.p.rapidapi.com",
        "X-RapidAPI-Key": "f71d44d641msh67207d481cd7a4ep1b0fc0jsna791dcdf928f"  # Replace with your RapidAPI key

      }
    #
    response = requests.get(url, headers=headers)
    upcoming_matches = []

    if response.status_code == 200:
        try:
            data = response.json()
            match_schedules = data.get('matchScheduleMap', [])

            for schedule in match_schedules:
                if 'scheduleAdWrapper' in schedule:
                    date = schedule['scheduleAdWrapper']['date']
                    matches = schedule['scheduleAdWrapper']['matchScheduleList']

                    for match_info in matches:
                        for match in match_info['matchInfo']:
                            description = match['matchDesc']
                            team1 = match['team1']['teamName']
                            team2 = match['team2']['teamName']
                            match_data = {
                                'Date': date,
                                'Description': description,
                                'Teams': f"{team1} vs {team2}"
                            }
                            upcoming_matches.append(match_data)
                else:
                    print("No match schedule found for this entry.")

        except json.JSONDecodeError as e:
            print("Error parsing JSON:", e)
        except KeyError as e:
            print("Key error:", e)
    else:
        print("Failed to fetch cricket scores. Status code:", response.status_code)

    return upcoming_matches

@app.route("/")
def index():
  cricket_scores = fetch_live_score()
  upcoming_matches = fetch_upcoming_matches()
  return render_template('index.html', cricket_scores=cricket_scores, upcoming_matches=upcoming_matches)

if __name__ == "__main__":
  app.run(port=int(os.environ.get("PORT", 8080)), host='0.0.0.0', debug=True)

Now we have to render the index page to see our API of the Cricbuzz application running also using the bootstrap to get it looking beautiful.

{% for score in cricket_scores %}
                <div class="col mb-4">
                    <div class="card custom-card">
                        <div class="card-body">
                            {{ score | safe }}
                        </div>
                    </div>
                </div>
{% endfor %}

Iterating it so we can get the output as follows

Also for rendering the upcoming matches the logic is settled as

{% for match in upcoming_matches %}
<div class="col mb-4">
                    <div class="card custom-upcoming-card">
                        <div class="card-body">
                            <ul class="list-group">
                                <li class="list-group-item">
                                    <strong>Date:</strong> {{ match['Date'] }}<br>
                                    <strong>Description:</strong> {{ match['Description'] }}<br>
                                    <strong>Teams:</strong> {{ match['Teams'] }}
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
{% endfor %}

The Output will look as follows

The overall index.html file will look as for rendering the cricket scores and Recent Matches

<!DOCTYPE html>
<html>
<head>
    <title>Cricket Scores</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* Custom styles */
        .navbar-brand {
            background-color: #d2dfd9; /* Change the background color */
            color: white; /* Change the text color */
            padding: 10px;
            font-size: 34px;
        }
        .top-bar {
            background-color: rgb(25, 25, 105); /* Change the background color */
            color: #e7f1f4; /* Change the text color */
            padding: 8px;
            font-size: 24px;
            font-family: Arial, sans-serif; /* Change the font family */

        }
        body {
            background-color: #030f13; /* Change the overall background color */
            color: #ece0e0; /* Change the overall text color */
        }
        .custom-card {
        width: 500px; /* Change the width */
        height: 250px; /* Change the height */
        /* Add any other styling properties as needed */
    }
    .custom-upcoming-card {
        width: 500px; /* Change the width */
        height: 150px; /* Change the height */
        /* Add any other styling properties as needed */
    }
    .navbar-brand {
        font-size: 24px; /* Change the font size as needed */
    }
    </style>

</head>
<body>
    <div class="top-bar">
        <div class="container">
            Cricbuzz Cricket Score
        </div>
    </div>
    <div class="container mt-4">
        <h2>Recent Matches</h2>
        <div class="row row-cols-1 row-cols-md-2">
            {% for score in cricket_scores %}
                <div class="col mb-4">
                    <div class="card custom-card">
                        <div class="card-body">
                            {{ score | safe }}
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>

        <h2>Upcoming Matches</h2>
        <div class="row row-cols-1 row-cols-md-2">
            {% for match in upcoming_matches %}
                <div class="col mb-4">
                    <div class="card custom-upcoming-card">
                        <div class="card-body">
                            <ul class="list-group">
                                <li class="list-group-item">
                                    <strong>Date:</strong> {{ match['Date'] }}<br>
                                    <strong>Description:</strong> {{ match['Description'] }}<br>
                                    <strong>Teams:</strong> {{ match['Teams'] }}
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>
    </div>

</body>
</html>

To run the application we can simply do it using the command

python3 app.py

#According to the configuration it will run at the location 127.0.0.1
# At PORT 8080
# The Application will run at the location
http://127.0.0.1:8080

The Working Demo of the application here looks as follows. The Application looks like this

DEMO of the Application :

If you like this content do try to implement it yourself; you will gain some confidence. Thanks for going by I hope you like the content putting a heart will give a boost to my morale to post such amazing content to you guys.

Do follow my endeavors here

Did you find this article valuable?

Support Code my World by becoming a sponsor. Any amount is appreciated!