Building Flask web application— Part 1
Prerequisite : First you need to install VS code.
Step 1 :
Create a new folder on desktop. Open it and hit right click inside it to open it using VS code as given below.
Step 2 :
Create main.py file in this folder as given below.
Open VS code terminal and install flask in it by running following command :
pip install flask
Write the code given below in main.py file
# Importing flask module
from flask import Flask, render_template# Flask constructor takes the name of
# current module (__name__) as argument
app = Flask(__name__)# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function home() and run the code written in
# index.html file
@app.route(‘/’)def home(): return render_template(‘index.html’)
# Flask's render_template() helper function is used to serve an HTML template as the response# so home page will render the form produced by index.html template
# main driver function
if __name__ == “__main__”:
# run() method of Flask class runs the application
# on the local development server.
app.run()
After writing code in main.py, DO NOT forget to save the code by clicking (Ctrl + S).
Step 3 :
Create a folder and it must be named as “templates”. (Remember lowercase “t”). Create a html file inside it “index.html” and write code given below inside it.
<html><body><h1>This is my first flask API</h1></body></html>
Folder structure must be as given below, otherwise it will throw error.
Step 4 :
Now run following command in the terminal :
python main.py
OR if above code doesn’t work, try :
python3 main.py
This will generate URL in the terminal, as shown below.
Copy and paste this URL in web browser and you can see the webpage as :
Congratulations !!!
You have created first flask API.
In next tutorial, let’s accept user input from API and perform simple mathematical operation and check output on the webpage itself.