Introduction to Routing in Flask

Gianni Castellano - Aug 2 - - Dev Community

Hello readers, I am going to give a brief introduction on an important concept in Flask, routing. It is used to direct incoming HTTP requests to the relevant parts of your application. Flask is a flexible and easy to use web framework designed to support the development of web applications. I will be using examples from my most recent Oldschool RuneScape Quest tracker application. There are four different methods used when creating your routes: GET, POST, PATCH/PUT, DELETE. The GET method will retrieve/view data from your API. POST will allow you to submit data via forms. PUT/PATCH allows you to update existing data. Lastly, DELETE, allows you to delete data.

This is done using the decorator @app.route followed by "/(specific route)", methods=["method"].

@app.route('/players', methods=["GET"])
def players_route():
    players = []
    for player in Player.query.all():
        player_dict = {
            "level": player.level,
            "id": player.id,
            "name": player.name,
        }
        players.append(player_dict)

    response = make_response(
        players,
        200,
        {"Content-Type": "application/json"}
    )

    return response
Enter fullscreen mode Exit fullscreen mode

As you can see at the top of this code we have the decorator followed by the route and the method we want to use on it. For this example we want to GET/Read/View the data from my players table in my API.

You might now be wondering what all the code under the decorator does. Well lets break it down! Our decorator tells flask to call the function "def players_route()" whenever a GET request is made the /players URL.

"players = []" is an empty list to store our player data. Next, we use a for loop to fetch all the players by using Player.query.all(). We then create a dictionary inside to loop in order to store our data in a JSON format. Lastly, we append the data using make_response to convert the player list to a JSON response. The 200 lets us know if the request was successful or not.

I hope you enjoyed this short introduction on Flask routing!

. . . .
Terabox Video Player