Flask API Tutorials

How to Create a Football (Soccer) App with the Football Science API

Introduction

There is no doubt that football is one of the most popular sports in the world. But sometimes it is really difficult to track all the upcoming events.

There are so many leagues and teams, which is why it might make sense to use a match scheduler to keep you up to date with what’s happening and when (especially if you’re involved in fantasy).

Today, we’ll help you take the first step towards becoming a football expert.

We will be using Python and the Football Science API to do this.

Connect to the Football Science API

What is the Football Science API?

The Football Science API supports 5 categories of endpoints:

  • timeline – here we can check past and future games. In the former case, it’s some kind of historical data. In the latter, the API returns a piece of information about upcoming events. Remember this endpoint, we will use it later.
  • match detail – detailed statistics about the specific matches. Besides usual insights, there is a very interesting commentary endpoint. It returns minute-by-minute info about game events.
  • list – returns a list of available tournaments.
  • world cup – this API has a special section for the biggest football event. Here you can find results, details and even tagged photos. It’s a very interesting group, especially in the analytics case.
  • live – real-time tracking of football games. It is the most important endpoint if you want to be updated with the newest actions.

As we said, we would like to create some kind of football guide.

It should display info about upcoming games in an efficient way. Additionally, it would be cool if the user can filter events by date.

Connect to the Football Science API

How to Build a Football/Soccer Application with Python

Our technical stack counts only one language – Python. So if you have it installed with version number 3.7+, you can hop aboard and move on.

As we would like to create something real-time and updatable, it is useful to work with web applications.

One of the best practices for this task is a Flask. It has everything you could need but it’s also very basic and lightweight.

1. Create a basic elements

Let’s create a project folder. Type this command in the terminal:

mkdir football-app

Now we should take care of a separate development environment. It is important for the portability of our project. Also, this approach allows you to leave the main system without unnecessary modules. Move to the football-app folder and execute the next command:

virtualenv -p python3.7 football-app-env

The virtual environment is ready, now we need to activate it.

source football-app-env/bin/activate

Now all python jobs are dedicated to the football-app-env, so required modules will be installed here. Paste the following line in the terminal for doing this task.

pip install flask requests

Besides the mentioned flask, we installed the requests module. It is very helpful in HTTP interaction. By the way, each endpoint has its own example code snippet from the RapidAPI team.

Now it’s time to establish the main file of the application. Create app.py file and paste there code as follows:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
return 'Hi, folks! Do you like football too? Glad to hear that!'

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

It is a template of the very first application on Flask. The expected result is to see the output message from our code. We can test it via one of the next terminal commands:

flask run

Or

python app.py

Now we need to visit the following link http://localhost:5000/, that’s because it is the current server address. The next image should look like this:

Great! The primal version of our app works.

Connect to the Football Science API

2. Add the Football API Integration

The next step revolves around API implementation. We will use the Calendar endpoint from the Timeline group. All required information (headers, URL and parameters) are in the middle and right API page sections.

Pay attention to the date range limit. It is an important exception, which should be used in the future.

Now it’s coding time. Add to our code the URL variables, which will be the final point of requests.

API_URL = 'https://stroccoli-futbol-science-v1.p.rapidapi.com/s1/calendar/{from}/{to}'
API_HEADERS = {
'x-rapidapi-host': 'xxxxxxxxxxxxxxxxxxxx',
'x-rapidapi-key': 'xxxxxxxxxxxxxxxxxxxx'
}

In the API_URL we left placeholders for the date ranges (from and to parameters). We will replace them according to the API docs in the future.

Now we need to execute the request with all required parameters and print the response. Modify the index function as it is shown below:

@app.route('/')
def index():
dates = {
'from': '2020-01-11',
'to': '2020-01-17'
}
request_url = API_URL.format(**dates)
response = requests.get(request_url, headers=API_HEADERS).text
return response

Don’t forget to add the importing line for the requests module.

import requests

Finally, our app.py looks like this:

import requests

from flask import Flask

app = Flask(__name__)

API_URL = 'https://stroccoli-futbol-science-v1.p.rapidapi.com/s1/calendar/{from}/{to}'
API_HEADERS = {
'x-rapidapi-host': 'xxxxxxxxxxxxxxxxxxxx',
'x-rapidapi-key': 'xxxxxxxxxxxxxxxxxxxx'
}

@app.route('/')
def index():
dates = {
'from': '2020-01-11',
'to': '2020-01-17'
}
request_url = API_URL.format(**dates)
response = requests.get(request_url, headers=API_HEADERS).text
return response

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

Now we can run our Flask application and visit its page again. The output should be close to this:

Excellent! We have just displayed the response from the server.

Connect to the Football Science API

3. Add some Design

Now we need to submit this in a more attractive way and allow users to customize the date range. To do this, we use the built-in features of the Flask framework and Jinja2 templates.

As a starting point, we need to create a folder for the markup files and call it templates. This is the default place, where Jinja2 looks for HTML-layouts. In the folder itself, create a file called index.html.

As it isn’t a guide about HTML and Jinja2 usage, we won’t give a detailed explanation about file structure. In short, we create a template with placeholders for Python objects. And when our app runs, those objects will have some data.

Full index.html code is in the following paragraph:

^<html lang="en">
<head>
<title>Football APP</title>
</head>
<body>
<div>
<form action="/" method="get">
<label for="date_from">From:</label>
<input id="date_from" name="date_from" type="date">
<label for="date_to">To:</label>
<input id="date_to" name="date_to" type="date">
<button type="submit">GO!</button>
</form>
</div>
<div>
{% if response %}
{% if response.status == 'error' %}
<p>ERROR! {{ response.message }}</p>
{% else %}
<table style="width: 100%">
<tr>
<th>Date</th>
<th>City</th>
<th>Event</th>
<th>Stadium</th>
<th>Season</th>
<th>Tournament</th>
</tr>
{% for event in response %}
<tr>
<td>{{ event.date }}</td>
<td>{{ event.city }}</td>
<td>{{ event.event_name }}</td>
<td>{{ event.stadium }}</td>
<td>{{ event.season }}</td>
<td>{{ event.tournament_name }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endif %}
</div>
</body>^

All code above has two parts: form and response. The first one is dedicated to the date range. The second checks for the response existence and builds a table with results.

After pressing the button, our form sends the next request:

http://localhost:5000?date_from=<some_date>&date_to=<some_date>

Basically, it throws date_from and date_to on our endpoint parameters. Our task is to modify the method so that, based on these parameters, it makes an API request.

We do it as follows:

@app.route('/')
def index():
date_from = request.args.get('date_from')
date_to = request.args.get('date_to')
if date_from and date_to:
request_url = API_URL.format(**{'from': date_from, 'to': date_to})
response = requests.get(request_url, headers=API_HEADERS).json()
return render_template('index.html', response=response)
return render_template('index.html')

As you can see, here we use the built-in method render_template and request. Don’t forget to add both of them in the import section.

import requests

from flask import Flask, render_template, request

So the current state of app.py should be as follows:

import requests

from flask import Flask, render_template, request

app = Flask(__name__)

API_URL = 'https://stroccoli-futbol-science-v1.p.rapidapi.com/s1/calendar/{from}/{to}'
API_HEADERS = {
'x-rapidapi-host': 'xxxxxxxxxxxxxxxxxxxx',
'x-rapidapi-key': 'xxxxxxxxxxxxxxxxxxxx'
}

@app.route('/')
def index():
date_from = request.args.get('date_from')
date_to = request.args.get('date_to')
if date_from and date_to:
request_url = API_URL.format(**{'from': date_from, 'to': date_to})
response = requests.get(request_url, headers=API_HEADERS).json()
return render_template('index.html', response=response)
return render_template('index.html')

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

4. Test the Application

Now we can check the application. Run it and visit the home page. The representation should look  like this:

Let’s choose some dates (e.g., between 2020-01-14 and 2020-01-20) and press the button:

Here you can track all possible football games in the set range. It can be used for calendar planning, choosing ‘what to watch’, etc.

But what would happen if we tried to choose a date range that’s too big?

This is it! Our plain and informative football-app is ready.

Connect to the Football Science API

Conclusion

Today we have created a new web application with a Football Science API. We have shown you the basic principles of API usage and Flask implementation. Our web project was created for educational purposes, so it has plenty of possible improvements. However, even in this version, it could be useful as a handbook to future matches.

This post shows how powerful and easy-to-use application programming interfaces can be. So if you would like to spend time on it and work on building a few interesting projects, there is no better time than now.

3/5 - (2 votes)

View Comments

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

3 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

3 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

1 month ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago