Python Flask Hello World Example
Python Flask - Hello World Example
In this tutorial, we will write a simple Flask application in Python, that returns a "Hello World" response when a request is made for the root URL.
Prerequisites
Python has to be installed in your computer. This is the only prerequisite for this tutorial.
Install flask using PIP
Run the following command to install flask library in your system.
$ pip install flask
Flask Hello World Application
We will build a simple, and lightweight Web application, where the server responds with the message "Hello World"
.
Create a python file with the following code.
main.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello World"
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8080, debug=True)
Open a Terminal and run this python program.
Now the flask application is running on localhost at port 8080.
Open web browser of your choice and enter the URL http://127.0.0.1:8080.
For the route /
URL, the server has responded with a message Hello World
.
Now let us break down the code in the python file main.py.
- From
flask
library, we importedFlask
class. - We created flask application using
Flask()
class constructor and stored it in the variableapp
. - We defined a function
index()
that is called for the root URL"/"
, which in this case would behttp://127.0.0.1:8080
, and returns string"Hello World"
. - We called the
run()
function on the flask applicationapp
and passed host IP address127.0.0.1
and port number8080
as arguments.
This is just a basic application to understand how to build a flask application.
Summary
In this Python Flask Tutorial, we learned how to build a basic server application with flask library.