Passing URL Arguments in Flask
In this article, we will cover how to Pass URL Arguments in Flask using Python. URL converters in Flask are mentioned in angular brackets (<>). These unique converters are designed to let us generate extremely dynamic URLs, where a part of the URL is regarded as a variable. For that we have created three different endpoints to understand three different scenarios of URL converters in Flask.
- Usage of a single URL converter.
- Usage when there are multiple URL converters.
- Use of type hints for addressing specific datatypes for values passed in the URL.
Consider the URL for each person’s social media profile page as an example of where we can have the URLs as –
Here, the base URL is https://www.faceconnect.com/home/user/ and 1001, 1002, and 1003 are the user IDs which extend the URL to point to the specific user’s homepage.
Single URL Converter
In this example, a single endpoint with the prefix “/home” has been built.
- The word “menu” has been put between angular brackets, indicating that it is a dynamic element of the URL. It will accept any text value.
- For instance, we attempted “/home/dashboard” (as seen in the output), which produced a dashboard as the value of the menu argument.
- However, attempting to visit “/home/,” “/home/dashboard/,” or “/home/dashboard/views” will result in an error, indicating that the path cannot contain additional routes and that the value must be present.
Multiple URL Converter
In this example, we’ve built an endpoint that has both a menu and a submenu, two dynamic parameters.
- Be aware that even though we utilise these arguments to create our route, we also provide them as parameters in the function declaration.
- This route will work for the URL where the home route is followed by two further routes.
- However, as indicated in the output, attempting to access “/home/dashboard/views/” will result in a failure.
URL Converter with DataType
The last example uses an endpoint that we developed to type-cast the dynamic URL to the specified data type.
- Here, we have said that an article ID, which must be of the integer data type, follows the article path.
- Therefore, the endpoint will successfully process any integer value that is passed to it in the route.
- It will give an error if it is unable to typecast the value to an integer data type, such as alphanumeric characters. (As shown by the output)
- It will typecast to the string data type by default if no type is specified.
Please Login to comment...