In this tutorial, we will build a flask app that places a certain fruit according to its biological classification. We will be using a few modules such as flask, a microframework web development library, and requests to make HTTP requests.
To begin let’s install these libraries.
pip3 install flask
pip3 install requests
Now let’s begin by creating a folder to store our files. You can call it anything, for this case I will call it flask-fruits. Inside the folder create a file called app.py and a folder called templates and insert a file called index.html.
This project will be implementing the fruitvice API.
Now let’s import a few modules in our app.py file.
from flask import Flask,request
from flask import render_template
import requests
import json
Let’s go ahead and initialize our app.
app = Flask(__name__)
Create a route and function to handle to get the fruit information. Add the following in the app.py file.
@app.route('/',methods=['POST','GET'])
def index():
if request.method == 'POST':
fruitname = request.form['fruit-name']
resp = requests.get('https://fruityvice.com/api/fruit/'+fruitname)
genus = resp.json()['genus']
family = resp.json()['family']
nutrients = resp.json()['nutritions']
order = resp.json()['order']
return render_template('index.html',genus=genus,family=family,nutrients=nutrients,order=order)
else:
return render_template('index.html')
The above code requests a fruit’s genus name, family name, nutrients in the fruit, and the order of the fruit from the API. The information is then rendered to the html template. Finish by adding the following.
if __name__ == "__main__":
app.run(debug=True)
Now let’s create our template in the index.html file we created above.
<!doctype html>
<html>
<head>
<title>Fruit Information</title>
</head>
<body>
<h1>Fruit Information</h1>
<form method="post">
<label for="fruit-name">Enter the name of a fruit:</label>
<input type="text" name="fruit-name" id="fruit-name" required>
<input type="submit" value="Submit">
</form>
<div class="fruit-info">
<p>Genus: {{ genus }}</p>
<p>Family: {{ family }}</p>
<p>Nutrients: {{ nutrients }}</p>
<p>Order: {{ order }}</p>
</div>
</body>
</html>
That’s it. Now start the server by running the command below.
python3 app.py
You can also use the command below.
flask run
You can now access your app by entering the address below on your browser.
http://127.0.0.1:5000
Your app should pop up as shown below. You can try any fruit you want.
There you have it. Thanks for reading.