Home » Tutorials » How to Master Dynamic Routes and Request Handling in Flask

How to Master Dynamic Routes and Request Handling in Flask

If you’re curious about taking your Flask skills to the next level, starting with the basics is crucial. That’s where our introductory piece, ‘How to Build Your First Web Application with Flask in PyCharm‘, serves as a springboard. It introduces the essentials of Flask through a simple project, paving the way for more complex topics.

Now, ready to expand your expertise, in today’s tutorial we will learn about dynamic URLs or routes, as well as the different types of requests: GET, POST, PUT, DELETE. So without further ado let us start.

Table of Contents

Necessary Libraries

In order to ensure the code functions properly, make sure to install the Flask library via the terminal or your command prompt:

$ pip install flask 

Imports

We start by importing the Flask class from the flask module so we can customize it later, then we import request which we will use to access the data sent by the user to our server, after that we import response which we will use to create and send custom responses to the user such as HTML.

from flask import Flask, request, Response

Creating a Flask Application Instance

Now we create an instance to customize our main class Flask so it will suit our needs for this code.

app = Flask(__name__)

Creating a Route for the Index Page

Following that, we create a route, which is essentially a roadmap telling our server where to direct the user when they visit specific URLs. For the URL generated by our application, we will establish a route. Upon visiting this URL, the index() function is triggered, guiding the user to the greeting message.

@app.route('/')
def index():
   return "Hello! Welcome to our personalized greeting app. Please add your name to the URL like this: /dynamic_get/your_name"

Creating a Dynamic Route with GET Method

Here, we will create a dynamic route that allows for modifications to the URL, leading the server to respond differently based on the user’s input, as we did here with the name and the age through the GET request, a method for retrieving information.

The dynamic_get() function extracts the name and, optionally, the age from the URL. The outcome of this process is demonstrated in the example below.

# Route for dynamic URL with GET method
@app.route('/dynamic_get/<name>', methods=['GET'])
def dynamic_get(name):
   age = request.args.get('age')
   if age:
       return f"This is a dynamic URL with GET method. Hello, {name}! Your age is {age}."
   else:
       return f"This is a dynamic URL with GET method. Hello, {name}!"

Handling Requests in Flask

Handling GET and POST Requests

All the previous routes were GET requests, now we will create a route that handles both GET (receive data) and POST (send data) requests, and returns a different response when either of them is called as shown in the example below.

# Route for handling GET and POST requests
@app.route('/data', methods=['GET', 'POST'])
def handle_data():
   if request.method == 'GET':
       return "This is a GET request."
   elif request.method == 'POST':
       custom_response = "This is a custom POST response."
       return Response(custom_response, status=200, mimetype='text/plain')

Handling PUT Request

We have seen the GET request and the POST request, now it’s time to tackle the PUT request which updates a resource and has the server respond accordingly, in the context of our code a message indicating that this is a “PUT request” will appear as shown in the example below.

# Route for handling PUT requests
@app.route('/update', methods=['PUT'])
def handle_update():
   return "This is a PUT request."

Handling DELETE Request

As the name suggests, the handle_delete() function is responsible for deleting a resource, and the server responds appropriately. in the case of our code a message indicating that this is a “DELETE request” will appear when a delete request is made to this route.

# Route for handling DELETE requests
@app.route('/delete', methods=['DELETE'])
def handle_delete():
   return "This is a DELETE request."

Running the Application

This part makes sure that this script can only be run directly and not imported as a module. As well as make the Flask development server accessible to all devices on the network on port 5000 and enable debugging.

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=5000, debug=True)

Example

You just need to visit the generated URLs to get to this page:

Here you need to add “/dynamic_get/name” to the generated URL to visit this page in my case “127.0.0.1:5000/dynamic_get/ramzi

Now add “/dynamic_get/name?age=num” to the generated URL to visit this page in my case “127.0.0.1:5000/dynamic_get/ramzi?age=26

Lastly, add “/data” to the generated URL to visit this page in my case “127.0.0.1:5000/data

As you can see, I cannot access the POST, PUT, DELETE requests via the web page, so I have executed them through the command line. This is because accessing these requests through a web page requires HTML.

Full Code

from flask import Flask, request, Response


app = Flask(__name__)


@app.route('/')
def index():
   return "Hello! Welcome to our personalized greeting app. Please add your name to the URL like this: /dynamic_get/your_name"


# Route for dynamic URL with GET method
@app.route('/dynamic_get/<name>', methods=['GET'])
def dynamic_get(name):
   age = request.args.get('age')
   if age:
       return f"This is a dynamic URL with GET method. Hello, {name}! Your age is {age}."
   else:
       return f"This is a dynamic URL with GET method. Hello, {name}!"


# Route for handling GET and POST requests
@app.route('/data', methods=['GET', 'POST'])
def handle_data():
   if request.method == 'GET':
       return "This is a GET request."
   elif request.method == 'POST':
       custom_response = "This is a custom POST response."
       return Response(custom_response, status=200, mimetype='text/plain')


# Route for handling PUT requests
@app.route('/update', methods=['PUT'])
def handle_update():
   return "This is a PUT request."


# Route for handling DELETE requests
@app.route('/delete', methods=['DELETE'])
def handle_delete():
   return "This is a DELETE request."


if __name__ == '__main__':
   app.run(host='0.0.0.0', port=5000, debug=True)

Happy Coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top