Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
Curious to learn how to build your own Flask routes to create dynamic web applications?
In this article, we will explore the concept of routing in Flask, a popular Python web framework. We will learn how to define routes and bind them to specific functions known as "views" or "controllers". We will also learn about the WSGI (Web Server Gateway Interface) specification which is the standard for web applications in Python. Additionally, we will see how to serve static files like HTML and stylesheets in a Flask application.
A route is basically a path to a specific file or a block of code which returns something. For example, when you visit a webpage, e.g., turing.com, your request will go to the server and ask for the files which are at path ‘/’. Similarly, if you go to turing.com/blogs, the request will be sent to the server asking for the files which are at ‘/blogs’. These files are mostly HTML, CSS, and JavaScript files that run in the browser.
Flask is a lightweight web framework written in Python. It is designed to provide simple and easy-to-use functionality for creating web applications and APIs. Flask allows Python developers to quickly and easily build web applications by providing a range of core features and tools, including routing, templates, and request handling. It is commonly used in combination with other technologies like HTML, CSS, and JavaScript to create dynamic and interactive web applications.
WSGI is a specification for web servers and web applications to communicate with each other. It defines a standard interface for web applications to accept requests and generate responses, allowing for interoperability between different web servers and applications.
Werkzeug is a WSGI utility library for Python that provides a range of tools and functions for working with WSGI applications. It includes a WSGI web server, a request and response object, and various utility functions for handling common tasks like URL routing and session management. Werkzeug is often used in combination with Flask to provide a solid foundation for building web applications.
Jinja2 is a template engine for Python that is commonly used with Flask. It allows developers to define and render HTML templates with placeholders and expressions, making it easy to generate dynamic and customizable web pages. Jinja2 provides a range of features, including template inheritance, filters, and macros, to help simplify the process of building and rendering HTML templates. It also offers sandboxed execution to ensure that templates are safe and secure.
There are several reasons why Flask may be a good choice over other Python web frameworks:
Flask has a minimalistic design and provides only core functionality, making it easy to learn and use. This can be particularly useful for small projects or for developers who want to have more control over the application's design and structure.
Developers can easily add custom functionality or libraries through extensions, allowing for a high degree of customization and flexibility.
The large and active community of developers and users provides a wealth of support and resources for those using the framework.
Flask has clear and detailed documentation, making it easy for developers to get started and learn the framework.
Flask is used by many well-known companies and organisations, including Pinterest, LinkedIn, and the Pallets Projects, which provides further assurance of its reliability and stability.
We now look at how to build routes in Flask with an easy-to-follow tutorial.
To build a route in Flask, make sure your machine meets these requirements mentioned below.
1. Open your terminal or CMD and run “pip install -U Flask” as demonstrated below.
2. Now, it’s time to open the IDE to write some code. For this article, we’ll be using VS Code. You can use an IDE with which you’re comfortable.
Let’s understand this line by line. First, we imported Flask into our py file which is necessary if we want to use external libraries. At line 2, we initiated Flask class to be able to use its methods and features. We stored Flask class into a variable named “app”.
As seen in the above Python code, at line number 3 we used the .route() method to create a route and created a function below which will be served when the specified route path is entered in the browser or API request.
The first argument in the .route() method is the path that needs to be accessed by the user in order to access the function. For example, if the route path is “/hello”, the function specified in the .route() method will be served when the user enters “/hello” in the browser or API request.
The route has other parameters too, such as a method with which we can define whether the function is about to post some data to the backend or whether it’s just for retrieving data from a server.
After creating the route, we will see how we can run that server in our local machine. A server running on a local machine means it can be accessed by other devices connected to the same wifi network. To run the server on localhost, we will have to use the .run method as written in the code above at line number 8.
Simply run the .py file to start the Flask server as seen below.
The .run method will start a server on the localhost port (default is port 5000). The server will be running and ready to accept requests from other devices connected to the same wifi network. Now, to test the route, we can use a tool like Postman or cURL to make a request to the localhost port and check if the route is working as expected.
If everything is fine, we can deploy the server to a remote host like Heroku or AWS so that it can be accessed by any device with an internet connection.
To test the server on localhost, you will need to open your preferred browser and type the server url as seen in the code above.
Congratulations! The server is working properly on the localhost and can be accessed by other devices connected to the wifi.
In Flask, templates are used to create dynamic HTML pages that can be rendered on the server and returned to the client as part of a response. This allows you to separate the presentation of your data from the logic that generates it, making it easier to maintain and update your application.
To use templates in Flask, you first need to create a template file that contains the HTML code for your page, along with placeholders for any dynamic content that you want to include. This template file can be written using the Jinja2 template language which provides a set of tools for working with templates in Flask.
Once you have created your template file, you can use the render_template() function in Flask to render the template and generate the final HTML for your page. This function takes the name of the template file as its first argument. Any additional arguments are used to provide values for the placeholders in the template.
You’ll need to create a folder in root named ‘templates’. All your HTML, CSS, and JavaScript files will be saved there. When a specific route will ask for that file, Flask will serve it as commanded.
Let’s see the action example below.
The first step is to create a template folder in the root directory of your project.
Inside that, create an index.html file and your HTML.
Next, create a Flask route.
Let’s understand how we created it.
The ‘render_template' function must be imported first (at line 1), followed by the creation of a new route (in this case), a new function, and the return of the 'render_template' function with your html file (filename with file extension). That's it. You can now see the HTML file being served by going to "/new-page".
Let’s go to the browser and see what happens.
Congratulations, it works! We’re done with the basics. But, what happens if we want to serve some values from the backend to the client side? Read on to find out.
What happens if data stored in a Python variable needs to be served? Jinja2 template engine is useful in this situation. Let's check it out in action.
First, you will need to define where you want your data to be served. Then, you will define that same thing in the Flask backend as well and ensure that the ID you use in both files are the same. Confused? Here it is.
As seen, at line 10, we’ve done something strange. That ‘{{name}}’ doesn’t look too good. However, that's a variable of Jinja2 template. In Jinja2, we create variables under “{{}}” curly brackets. Under that, anything we write is considered a variable.
Let’s see what shows in the browser.
Why is there nothing? That’s because we didn’t configure the backend to serve the ‘name’ variable. Let’s do it.
Let’s understand this step by step.
First, we declared a variable at line 11 named ‘myname’ and stored a value ‘Turing’ in it. Then, in render_template we can pass that variable as an argument and restart the Flask server.
Note: When passing the argument, we need to use the name that we used in HTML otherwise this won’t work.
We can check in our browser that it’s working perfectly.
In web development, the request methods are a standardized set of actions that a client can make on a server. These actions are typically carried out when a user interacts with a web application, such as when they submit a form or click on a link.
The most commonly used request methods are GET, POST, and DELETE. The GET method is used to retrieve information from the server. The POST method is used to submit data to the server and the DELETE method is used to delete data from the server.
The specific request method used in a given situation depends on the type of action that the user is taking and the kind of data they are working with. For example, if a user is filling out a form to create a new account, the web application would typically use the POST method to submit the user's information to the server. On the other hand, if a user is viewing a page on a website, the web application would use the GET method to retrieve the content of that page from the server.
Overall, the request methods are an important part of how web applications work as they enable clients to interact with servers in a standardized way. This allows web developers to build complex and dynamic web applications that can handle a wide range of user actions and data.
In Flask, you can handle different request methods in a route by using the @app.route() decorator and specifying the methods that the route should handle. For example, to handle GET and POST requests in a route, you would do something like this:
To access request data, you can use the request object, which is a global variable in Flask that represents the current request. For example, to access the query string parameters in a GET request, you can use request.args. And to access the data in a POST request, you can use request.form.
To respond to a request, you can return a response from the route's function using the make_response() function which creates a Response object that you can return from the route. For example, to create a simple text response, you could do something like this:
Alternatively, you can use the jsonify() function to create a Response object that contains JSON data which is often more useful when building APIs. For example:
Flask includes a built-in mechanism for dealing with errors that occur while the application is running. To use its built-in error handling feature, you first need to import the abort function from the werkzeug.exceptions module which is a dependency of Flask. This function allows you to raise an HTTPException and return a specific HTTP status code to the client.
Here is an example of how to use the abort function to return a 404 error (indicating that the requested resource could not be found) to the client:
In this example, the get_user function is a Flask routing handler that is called when a client makes a request to the /users/<id> endpoint. If the specified user cannot be found, the abort function is called with a 404 error code that causes Flask to return a 404 error to the client.
You can also use Flask @app.errorhandler decorator to create custom error pages for specific error codes. Here is an example of how to use the Flask route decorator to create a custom error page for 404 errors:
In this example, the page_not_found function is decorated with @app.errorhandler and passed the error code 404. This means that whenever a 404 error is raised while the application is running, Flask will call this function and return the response generated by it to the client. The function returns the rendered template 404.html and a 404 status code that will be sent to the client.
Flask's built-in error handling features can be very useful for creating user-friendly error pages and returning appropriate status codes to the client when errors occur in an application.
Flask's Blueprint feature allows you to organise your Flask application by grouping related routes together in a blueprint that you can reuse in multiple Flask applications. This can help make your code more modular and easier to maintain.
To use the Blueprint feature, you first need to create a blueprint object. You can do this by calling the Flask.blueprint method and passing in the name of the blueprint and the import path of the module that contains the blueprint.
Here, the users_bp variable is a blueprint object that is named users and is defined in the module at the import path "name".
Once you have created a blueprint, you can then define routes for it in the same way that you would define routes for a Flask application. For example:
In the above example, the get_users and get_user functions are route handlers that are defined for the users_bp blueprint. These functions will be called when a client makes a request to the /users and /users/"<id>" endpoints, respectively.
Once you have defined the routes for your blueprint, you need to register it with your Flask application. This can be done by calling the Flask.register_blueprint method and passing in the blueprint object:
Here, the users _bp blueprint is registered with the Flask application app. This means that the routes defined in the blueprint will be added to the application and can be accessed by clients making requests to the application.
Flask provides a number of built-in functions for generating URLs for specific routes in an application as well as for redirecting the client to different pages.
To generate a URL for a specific route in your Flask application, you can use the url_for function. It takes the name of the route as its first argument and any additional arguments are used to fill in the placeholders in the router's URL pattern. For example:
In this example, the get_users function generates URLs for each of the users in the users list by calling the url_for function with the name of the get_user route and the ID of the user. The generated URLs are then passed to the users.html template which can use them to create links to the individual user pages.
To redirect the client to a different page in your Flask application, you can use the redirect function. It takes the URL of the page to which you want to redirect the client as its argument. You can generate the URL using the url_for function as shown above, or you can pass a string containing the URL directly to the redirect function. For example:
Here, the get_user function checks if the specified user exists. If not, it redirects the client to the /not-found route by calling the redirect function with the URL generated by the url_for function. This will cause Flask to return a 302 redirect response to the client which will automatically redirect the client to the specified URL.
Flask's URL building and redirecting features can be very useful for creating user-friendly and easy-to-use web applications. They allow you to generate URLs for specific routes in an application and redirect the client to different pages, making it easy to navigate between different parts of the application.
We’ve learnt all about the basics of how to build routes in Flask along with serving static files and getting data. We discussed what a route is, explored Flask, and covered the Jinja2 template. We also built a basic Flask server in a local machine. To expand your understanding, consider experimenting with your own code.
Anas Dew is a full stack developer, content creator, and tech writer who also runs his own tech blog. He has built 8+ products and MVPs including web apps and SaaS.