Routes & URLs - Flask Tutorial Series #2
Key Takeaways
This video tutorial series covers routes and URLs in Flask, including URL processors, URL parameters, dynamic URLs, request methods, and custom status codes.
Full Transcript
what is going on guys welcome back in this second episode of the FL tutorial series we're going to cover a bunch of different topics including routes URL parameters URL patterns and processors Dynamic URLs as well as the different methods that we can use to send a request and how to return custom status codes so let us get right into [Music] it all right so let us briefly recap what we did up until until this point we created a virtual environment for our application so that we only have the packages that are relevant to this project that we're building here and we created this simple hello world application in flask the idea is we import from flask flask with a capital f we create an application and then we add this index function which just returns hello world as a heading this is just some HTML code here and then we map this index function to the default route slash and then all we have to do is we have to run the application with the host 00 0 which is automatically Local Host and also the private local IP address then we also customized the port to be 5555 and we said debug to True which has the effect of us not having to constantly restart the application to make changes or to apply changes uh it happens when we change the code and we also see the error messages instead of something like internal server error without any context so what we're going to do in this videoos we're going to learn about routes we're going to learn how to handle different types of um URLs so how handle Dynamic URLs also how to handle URL parameters and we're going to learn about the different types of requests like post and get and put and so on um and we're going to also learn how to return custom status codes so let us start with a very simple thing first let's just add another endpoint here which has a different route so we can say here another function let's say hello and this function will also return just a simple hello world maybe not as a heading this time time uh what we can do easily is we can just say app. route and the route can be something like SL hello the important thing is every route one has to start with a slash so we have to say slash and then something and you can call this route whatever you want you can call it hello you can call it hello world you can call it ABC it doesn't matter and it doesn't even have to match the name of the function so I can call the route XYZ and I can call the function hello this is also fine and by by doing that you can basically add as many end points as you want so what you have to do is you have to run the application and then you can just say slash hello and then you will get to this endpoint uh that is mapped to the function or that the function is mapped to now this is all static so I can add a bunch of those and they're always going to be the same however what I can also do is I can add certain or so-called URL processor so I can have variables in the URL itself that I can hand handle in the function so for example what I can do is I can create an endpoint here a route uh which I can call slash greet and then what I can do is I can add uh a name here so I can say I want to greet a certain name and how I can do that is I can use angle brackets to specify name here so now it's not greed and then slash angle brackets name this is not the endpoint but name is now a variable that can be dynamic so I can say greet mic greet uh Bob or something like this and the way I handle this is I create a function and the function takes the parameter name so in this case what I could do is I could say FST string hello and then name so the idea is now in the URL itself I have the parameter name and I can go to the route greet SL mik and I would get a different response than when I go to greet SL Bob for example and uh we can see that this is the case by just going to SLG greet SL Mike and there you go hello mik SLG greet SL Bop hello Bob so this is what is called a URL processor now there are certain things that we can add to these URL processors so for example if I have a route um let's call it at so slad and what I have here is number one and number two then what I can do is I can Define the function add which takes the parameters number one number two but you're going to notice something if I return for example an F string saying number one + number two is equal to number one + number two what you will notice is that when we go to the application and I actually go to add sl10 sl20 you will see that the result is 1020 and of course this is because what happens by default is that the parameters that we pass are considered to be strings so there are just concatenated so the string 10 plus the string 20 is of course 1020 that's a string concatenation if I actually want to do a calculation I have to typ cast these parameters so what I can do of course is I can say number one equals int number one but I can also just specify the data type of the parameter of the um of the it's a URL parameter of the um value that is passed here as part of the dynamic URL I can specify it here in the route already so I can say it's an INT colon number one and it's an INT colon number two so what happens here now is that this is considered to be uh an integer already so I can say at 1020 and you can see 10 + 20 is 30 what happens now is though when I pass something else so when I say 10 hello I get not found because this is now obviously a string it cannot be typ casted into an integer and this route is only for integers so if I pass something that's not an integer it doesn't even have the route it doesn't find the mapping so those are or this is how you do Dynamic URLs those are URL processors what we can also do is we can pass actual URL parameters and maybe you've seen this or probably you've seen this um on a couple of websites you go to something like uh login now hopefully it's not done like this this is very insecure uh but you usually have something like login and then question mark username equals and then something and then you have an ant and then you have password equals and again hopefully it's not in clear text in the URL but these are URL parameters if you see them somewhere so how can we handle those in flask what we can do is we can do the following app route and then maybe let's call this handle uh the suggest questions you see here are by the way from my prepared code it just thinks that I'm going to write all the stuff again and I actually am uh so handle query or handle URL parms let's call it that way uh handle URL parameters and the function is going to be handle pars or something like this uh now we don't need to pass anything here now as a parameter the parameters here are taken from the URL so if I have uh these URL processors here they're going to be part of the function signature if I handle the actual URL parameters it's happening by uh using a so-called uh or using the request instance so what I have to do is I have to say from flask import flask and also request and then it's going to be part of the request uh object so I can do here or actually I can return uh the string version of request. arguments so I can just return this as a string version and then I can go to handle uh what was it handle URL params and you can see it's an empty dictionary so it's an empty immutable dictionary but if I add now some parameters so uh question mark name is equal to mic then you can see I have name and Mike in here and if I say and greeting is equal to hello you can see I have name mic greeting hello so what I can do here is I can say that I want to handle the following thing the greeting is going to be equal to request. arc. getet and I can say here greeting and the name is going to be the same thing with Name by the way this is a dictionary so you can also instead of saying get you can just do this this also Works um and then we can return for example an FST string that says greeting and then name so when I go back I can just go to slash handle URL parameters and then name Mike greeting hello hello Mike so this is how you handle the URL parameters now of course if one is missing this is going to to give me a bat request key error so it makes sense to check if we have all the parameters available we can do something like if greeting in request arguments. keys and name in request arguments do Keys then we do all this otherwise we return some parameters are missing uh so now if I do this I get some parameters are missing and if I go to this I get hello mic all right um so this is how you handle the uh URL parameters now if you have a post request you actually get uh a form we're going to talk about this I think in the next video so we're not going to handle the post parameters yet so not we're not going to handle forms that actually um include uh include information that we pass with a post request however what we are going to do is we're going to learn how to handle different types of requests because all these routes all these endpoints that we Define here are by default only handling get requests so we can see that this is the case by opening up a terminal uh I'm not sure if this works out of the box on Windows it does work on Mac and Linux uh you can use the tool curl and if you don't have curl just just install curl using your package manager uh and curl basically just sends a request so I can say HTTP colon uh then Local Host slash hello for example and of course I need to specify the port which is 5555 uh and you can see I get Hello World here uh as an answer so I can just send a simple get request to an endpoint and I get whatever this endpoint returns to me now what I can do is I can also specify the method so I can say curl DX so capital x and then post to specify that now I'm sending a post request to the same same endpoint and what you can see here is I get as a response 405 method not allowed so the post method is not supported by this endpoint now if we want to change this if we want to allow for post requests we need to Define this in the route definition so for example if I want to allow for post requests on the endpoint hello what I have to do is I have to say methods equals and then I have to pass a list of all the methods that I want to support on this endpoint by default this list looks like this it's just get however I can also say it's just post if I specify it like that get requests are no longer allowed so I can save this I can open up my terminal and I can say curl um HTTP colon1 12701 5555 and then SL hello you will see it now tells me method not allowed even though I didn't specify post or exactly because I didn't specify post whereas if I say DX post you will see I get hello world so if I want to support both I just have to say get and post and then I can run the same thing it worked and I can also run just uh now the displaying is a little bit messed up there you go I can also do it with get and I also get the same response now the difference between get post put delete is not really uh a technical one primarily it's primarily a convention you use get when you want to get a resource when you want to get information you use post when you want to submit information so when you want to create something uh you use put when you want to update information so when there is for example uh if you have a to-do list application you already have an existing to-do you want to change something about it you use put and if you want to delete it you use delete so those are the four main methods there are also others but we're going to focus on those four uh and you can basically just specify that you want to allow for put you want to allow for delete and so on maybe you only want to allow for delete but this is how you use them get to get information post to create information or to submit information put to change information delete to delete information um now let's say you support multiple of these methods on the same endpoint how can you differentiate between the two uh or between the three or four let's say I have get post here what I can do is I can say if request. method is equal to get then I want to have a certain kind of behavior so then I want to return for example here um you made uh get request then I can say l if request method is equal to post then I can just print you made a post request now you can also if you want to add an else Branch but this is not going to be relevant because the proper message here is you will never see this message because of course we cannot send a put request or a delete request or anything else to this endpoint you will always only get a get or a post request so I can go again into the terminal maybe let's go ahead and also add a back sln in the end just so we have a line break so that we don't have to constantly mess up the formatting in uh in the command line so I can send this request you made a get request I can send a post request you made a post request and what you usually do later on we're going to learn about templating and using HTML files and so on uh what you usually do is you have one endpoint that does something and when you send a get request to that endpoint you get the HTML template so you get basically the form to fill out with maybe create a new to-do you get um when you send a get request to this create to-do page you get the form that allows you to create or to specify the new to-do and then when you click the submit button you send a post request to the same endpoint to actually create um the to-do so in the get Branch you would serf the HTML file and here you would actually process the information from the form um all right so this is how you handle the different methods now last but not least I want to show you how you can return a custom response so how you can uh specify the status code that you want to return and for this we're going to actually also use the hello hello here let's go back and just return hello world and let's only allow for get again um what we can do here this is the simple way to do it we can just specify the status code by passing uh or by returning it as a second value here so I can just say comma 200 and this will return a 200 status code now I think 200 is the default we can see if that is the case by just going again into the terminal and let's just add a again here for formatting recent back sln uh we can go ahead and say curl but I can also specify here Dash uh what was it I wrote it down here um I think it's- i- capital I to get the response header so you get HTTP 200 okay and then you get also the content type the content length you can see it's text HTML uh it's content a Content length of 12 and so on now I can change this by just saying comma 2011 which is created so you usually use that after a post request I can just curl again and you can see here now I get 2011 created I can also change this to 202 and then you get accepted I can also change this even though it doesn't fit here I can also change this to 404 which is not found and you can see I get not found I can also change this to 500 which is I think internal server error there you go I can also change this to 501 which is something else not implemented and I can also change this to something like 936 uh which I don't even know what it is unknown there you go or I can change this to something like this I'm not sure if this is going to be rejected uh yeah unsupported Response Code and HTTP response so I have a video on this channel where I explain the different status codes when to use which one and what they basically mean I'm not going to go through all this here here just know 200s are basically to tell you that uh everything worked fine 300s are for redirection uh 400 is telling you you did something wrong and 500 is telling you the server messed up something that's like the most important thing to know um now we can also go ahead and create a full custom response so we can go and say from flask import flask request and make response and then we can craft a full response we can say response is equal to make response and then we can do things like response. status code is equal to 202 for example and then we can also say response and I can actually or response. headers and I can actually manipulate things like content type is going to be equal to and I can change this to application SL octet stream for example or Json or text plane or something like this so I can go now and you can see we get actually we don't get this because we were still returning hello world we need to of course return the response there you go you can see now 202 accepted content type application octet stream uh and of course now we we don't have any text so we would have to add here hello world back sln to have the content there you go and we still have content length 12 and if I just do it like this I still get Hello World um we can also change this here to text/plain which is more fitting I guess there you go text plane 202 accepted and this is the content so this is how you can craft custom responses so that's it for today's video I hope you enjoyed it and hope you learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you on the next video and bye
Original Description
In this video we learn how to work with routes and URLs in Flask. We learn about URL processors, URL parameters, dynamic URLs and also about the different request methods as well as how to return custom status codes.
◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
🐍 The Python Bible Book: https://www.neuralnine.com/books/
💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
👕 Programming Merch: https://www.neuralnine.com/shop
💼 Services 💼
💻 Freelancing & Tutoring: https://www.neuralnine.com/services
🌐 Social Media & Contact 🌐
📱 Website: https://www.neuralnine.com/
📷 Instagram: https://www.instagram.com/neuralnine
🐦 Twitter: https://twitter.com/neuralnine
🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/
📁 GitHub: https://github.com/NeuralNine
🎙 Discord: https://discord.gg/JU4xr8U3dm
Timestamps:
(0:00) Intro
(0:27) Recap
(1:44) Routes
(2:45) Dynamic URLs
(6:18) URL Parameters
(10:35) GET, POST, PUT, DELETE
(15:48) Custom Responses & Status Codes
(19:46) Outro
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeuralNine · NeuralNine · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
Python Beginner Tutorial #5 - Loops
NeuralNine
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
Python Beginner Tutorial #7 - Functions
NeuralNine
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
Python Beginner Tutorial #9 - File Operations
NeuralNine
Python Beginner Tutorial #10 - String Functions
NeuralNine
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
Python Intermediate Tutorial #6 - Queues
NeuralNine
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
Python Intermediate Tutorial #9 - Recursion
NeuralNine
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
Python Intermediate Tutorial #11 - Logging
NeuralNine
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
Python Machine Learning #4 - Support Vector Machines
NeuralNine
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
Making Text Images Readable Again with Python and OpenCV
NeuralNine
Neural Networks Simply Explained (Theory)
NeuralNine
Motion Filtering with OpenCV in Python
NeuralNine
Top 5 Programming Languages To Learn in 2020
NeuralNine
Simple TCP Chat Room in Python
NeuralNine
Image Classification with Neural Networks in Python
NeuralNine
Edge Detection with OpenCV in Python
NeuralNine
S&P 500 Web Scraping with Python
NeuralNine
Simple Sentiment Text Analysis in Python
NeuralNine
Introduction - Algorithms & Data Structures #1
NeuralNine
More on: API Design
View skill →Related Reads
📰
📰
📰
📰
I Did the Math on Claude Opus 5: Max Effort Cost 94% More Than High Effort
Dev.to · tokenmixai
I Banned AI Tools From My Creative Process for 30 Days. Here’s What Happened to My Brain
Medium · AI
Best AI Tools for Content Creators With Zero Budget
Medium · AI
Stop Building AI Chatbots. Build These 7 AI Products Instead.
Medium · Machine Learning
🎓
Tutor Explanation
DeepCamp AI