FastAPI and Pydantic - URL Query Parameters for Filtering

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to take a look at query parameters in fast API we're going to see how to add parameters to our URLs and then access those within our fast API Handler functions so we have the page on query parameters open here we're going to look at that in a second but let's go to this Wikipedia page and we're going to see what a query parameter actually is before we start this video and I'll leave a link to this page below the video If we go to the structure of a query parameter you can see that we have the URL here that contains the domain and the actual resource the link to the resource but then after that part of the URL we have this question mark which is going to say to the URL that anything that comes after that is a query parameter and a query parameter has a key in this case it's called name and a value which in this case is feret and you can have a URL that contains multiple query parameters so for example again the question mark and then we have that same key and the different keys and values are separated by the Amper sand operator and we have a second query parameter called color after that so how do we work with these in fast API let's go to the documentation and we can declare function parameters that are not part of the path parameters that we saw a couple of videos ago so a path parameter will have some reference in the URL if we Define an argument to these functions that is not present in the path parameters then by default What fast API is going to do is interpret them as query parameters and if we scroll down here you can see that it's a set of key value pairs that go after the question mark As we saw on the Wikipedia page so if we Define a URL like this that contains a query parameter skip and a limit then those two values Skip and limit will be passed into the function as you can see here and you can give them type hints and also default values and that type hinting is important as it says here when you declare your query parameters in the arguments with python types they are then going to be converted to that type and validate ated against it so enough talking let's go to VSS code and what we're going to do is we're going to open this project that we worked on so far in the series and we're going to go back to the main. pi file where we defined our end points now a couple of videos ago we added this genre endpoint and the path here that's passed Into The app.get Decorator that contains that path parameter for the genre but what we're going to do in this video is completely remove this and we're going to add that query parameter into the list in point so we're going to switch that up and we're going to define the genre query parameter in the URL and then this endpoint here this Handler function in fast API is going to take that query parameter for the genre and it's going to then do some filtering if it exists for all of the bands that we have in that list that we've got above here so what we're going to do is we're going to add a parameter to this API Handler function and we're going to copy the genre parameter that we had from our old endpoint here and we're going to paste that in to this function here so now the function is going to look for a query parameter in the URL called genre and that will be an instance of the genre URL choices that we had and that's the python enum class with the available genres but what we also want to do is we want to allow this to be null and that's because by default in a list endpoint we don't always want to specify a genre we might want to return every single band from the back end the genre is going to be used to filter the return bands if it exists but if the URL is just plain SL Bands then we want to default that value to none and we also need to give it that a union type of genre URL choices or none so just to clarify in the URL we might have a genre and if we do we expect it to be that particular enum type but if we just want to return all of the Bands it's going to have the value of none that query parameter and we're then going to default the value to none as well and when we default the value to something it means that the query parameter is not required it might be left out of the URL we'll see that in a second now we need to redefine the logic for this Handler function we're going to check if we had a genre in the URL and if we had a genre we're going to return a different list comprehension than the one that we have at the bottom here and I'm going to make this bottom one on a single line so at the bottom we're just converting every single band to that pantic model and returning a list of those bands but in the F statement here if we have a genre we need to do some filtering so what we're going to do is return a different list comprehension and again we are going to convert each band that we find to that band pantic model and that's for all B and bands but we are going to add the condition now to this statement and the condition is going to be copied from what we had before where we look at the dictionary and we look at the genre and we lowercase that value and check if it's equal to the value coming in in the URL so we're going to copy this section of the code and we're going to paste that into this Handler here so we might have that query parameter in the URL and if we do have it we are going to then filter down the list of bands to only the bands where the genre field matches what's been passed as that query parameter and for all of the resulting objects we convert them to a pantic model and return those if we don't have a genre in the URL we're just going to default to returning the entire list of bands so I hope that logic makes sense let's now start the uicorn server on the terminal and we're going to pass the reload flag into that that's going to start the server on Local Host 8000 so I'm going to copy this URL and we're going to go to the browser now if we go to the SLB endpoint we get a list of all of the Bands but what we're going to do is we're going to add a query parameter for the genre and we're going to try and filter those bands down to only the bands that match that genre for example that match rock music so let's change the url at the top here hope you can see that we're going to add a query parameter by specifying the question mark and then the key name is going to be genre and we're going to set that equal Al to rock so let's now execute that and you can see we only get back that one band whose genre matches what's in that query parameter and if we go back to VSS code and go to the top here I have The Kinks and that's the only rock band I'm just going to copy that to the line below so now we have two rock bands all be at the same one and we're going to go back to the page and this time we get both of those because again the genre is matching what's in the query parameter and again if we remove the query parameter we get back all of the bands now what I'm going to show you is that this statement here that we have in the URL where we set the default value to none that makes the query parameter optional but if we remove that default value and go back to the page this time when we go to the URL without that query parameter we're getting an error and that's because when we don't set the default value fast API will expect that you're going to send that query parameter all the time and therefore you get that error so if you want to make the query parameters optional in the case of this endpoint you can set a default value and that will prevent fast API from returning that error and one other thing to note here is that because we're using the genre URL choices we get that data validation built in when we use that enum class so if we go back to the page and this time I'm going to refresh and we're going to specify the query parameter and let's set the genre this time to electronic the response here gives us back the one band with that genre but if we change it to something that's not in the enum we get back that error as we saw before so we get the built-in validation by using the enum type and as I said in the original video that can be very useful for example if you have a massive database full of data and you want to do a search based on a query parameter in the URL that will incur a full table scan unless you have an index on that database table and adding an enum such as this one can limit the possible values that you're sending to the database to a predefined list and that can avoid those Full Table scans if someone sends you something that that doesn't make sense now what we're going to do just to finish the video is we're going to show that we can add multiple query parameters to the URL and this is going to be a kind of trivial example but what I'm going to do is go back to the browser and as well as getting all bands that match a particular genre we can add a second URL query parameter and let's say we have another one called has albums that we want to set to true and that will default to false so a request to this URL with these query parameters here would look for all ronic bands who have released albums now you can see at the moment we have an albums key in this response and it's an empty list when we specify has albums equals true we want to return only bands that actually have albums in that list and because we have the two query parameters here we want this to be an and condition so genre equals electronic and has albums equals true so how do we do that let's go back to VSS code here and I'm going to add another parameter to this function so let's do this this on new lines just to make it clear what's going on and as well as the genre query parameter let's add another one called has albums and we're going to specify the type for that one as a buan type and we're going to default that to false and what we're going to do is build up the code in this endpoint so we're going to start with this statement here where we convert every single object to a pantic model and I'm going to create a variable called band list and set it equal to that list comprehension and then we can filter out the values that we don't want to return from the endpoint now if we have a genre in the query parameters what we're going to do is we're going to reference this band list so I'm going to change the list from the bands to this band list that we have and we don't need to convert that to a pantic model anymore so we're just going to return every band in that band list if the genre and I'm going to use the dot notation because we're accessing a field on an object if that genre within that band is equal to the value in the query parameter and what we also need to do here is we need to reassign the result of this St statement to the band list so if the genre exists we take that band list and we filter it down to only those that match the genre here in the URL and we need to add another check just below this if we have the has albums parameter in the query parameters we're going to do some further filtering of that band list and we're going to set that equal to another list comprehension and again we're going to Loop over all bands in that band list that we've defined above and again we're going to add a condition to this and this time the condition is we're going to look at the length of each band's album's property and remember that's a list of the album type and in this case we're only going to return bands who have albums so we're going to check that the length is greater than zero and you could also omit this condition here and just look at the length because if it's zero that's going to evaluate to false anyway but I do like to be or I do prefer to be explicit with these statements so the final thing to do is actually just return the band list rather than that list comprehension and let's quick L go over this one more time so we understand what's going on we convert every band to a pantic model and we set that in a variable called band list and then we are going to check if we have those query parameters and do further filtering in each case firstly we look to see if we have a genre and then we filter down that band list to only the bands that match that genre and then we also look to check if the has albums query parameter is true and if that's true we do some further filtering and check whether that particular band has has some albums and this is an and condition because we are filtering at each step so if both of them are true the first one is going to reduce the list to only the bands that match the genre and the second F statement is going to further filter that down to only the bands that match that genre but also have albums and the key Point here is that we can pass these query parameters and we can pass as many as we like to the fast API function and if we pass these default values they are not going to be required they're going to be optional parameters in the URL so let's now save this file and we're going to go back to the browser now we had this endpoint before that was just looking up the genre and checking if it was equal to electronic if we add has albums equals true we expect to see this disappear because this particular artist does not have any albums in that list so if we send a request with these query parameters this time we get back an empty list and we can remove the has albums part of that and we get back the original response and we can actually remove gen Al together we can only look for groups that have albums and we can set that equal to True here and we get back that single band that has albums in the list we have a duplicate in that list that was from the last video but this is actually the response that we're expecting because we only want to get back the bands that do have albums so we can chain together the query parameters in the URL and pass the key values as arguments to the fast API function in order to get those arguments and then option we can perform type hinting type conversions and data validation very useful functionality in fast API and also of course if we need to set some of these query parameters as optional we just give them a default value and then we can handle the logic within the body of the Handler function now one last thing I want to show is the Swagger documentation for our API if we go to the slash bands endpoint here that's the one we've added these query parameters to you can see in the documentation that it's added genre and has albums as parameters to this endpoint and notice that it says query here that's because it knows these are not path parameters and that's because it's not defined in the URL for this function the URL doesn't contain any parameters so fast API knows that these are query parameters and it also gives you some useful information about the types in this case a Boolean type with a default value of false so as always the documentation works really well with these query parameters and the types in Python so that's just something else to show at the end of this video thank you for watching the video if you've enjoyed it please give it a thumbs up and subscribe to the channel if you've not already done so and we'll see you in the next video
Info
Channel: BugBytes
Views: 1,503
Rating: undefined out of 5
Keywords:
Id: Dnp07ZKfdVU
Channel Id: undefined
Length: 14min 16sec (856 seconds)
Published: Mon Dec 04 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.