DEV Community

loading...

Getting Started with Flask

Carlos Magno
Introvert, Web Developer, Hobbyst Illustrator and CS Student;
・2 min read

Hello there. Today we are going to take a look at Flask, which is a lightweight web application framework and it's really easy and quick to get started. Flask is really great for building APIs and Webapp's backend. So, first of all, you are going to need to have Python and Pip installed on your computer. If you don't have them installed, you can do so giving a look at the oficial website.

Now we need to install Flask. We can install it with Pip:
pip install Flask

Now that we have Flask installed, we can now create a folder to hold our project. In this project, we'll create a file named main.py. This file will be the heart and body of our flask application.

To build a Flask application, we are first going to import our dependencies and then instantiate our flask application:

from flask import Flask, request, jsonify
import time

app = Flask(__name__)

After all, we'll start to define our application's routes. In Flask, we define routes using the decorator @app.route() above a function and passing two arguments: the path and the allowed methods. In this case, we are providing '/' (root) as path and allowing only the GET method in this route. The function init, will then return H3ll0 W0rld which is exactly the request's response.

@app.route('/', methods=['GET'])
def init():
    return 'H3ll0 W0rld'

After all the routes, we must now start to run the application. It can be done with the run() method of the application instance.

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

Now we can finally run our flask app and test out the routes. Save the file and run the script: python main.py. We can then open our browser and access localhost:5000 to see the output.
accessing '/' route

We can also return HTML code and pages when handling a request:

@app.route('/link', methods=['GET'])
def link():
    return '<a href="#">Link to nowhere</a>'

Link to nowhere

It's only that for today. Just like Python, Flask is very expressive and easy to get into. You don't need to learn much to start applying it in real problems and solutions. You can learn more at flask docs. Thank you for reading until the end!

Discussion (0)