Fast API Tutorial, Part 3: Query Parameters
Summary
TLDRThis FastAPI tutorial video explores the concept of query parameters, essential for dynamic searching in web applications. It demonstrates how to set up query parameters in a route using 'skip' and 'limit' to paginate results. The tutorial also covers making parameters optional and leveraging Pydantic's type conversion capabilities. Viewers learn to handle path and query parameters together and understand the importance of parameter ordering in function declarations. The video concludes with a look at required query parameters and a preview of upcoming content on request bodies.
Takeaways
- 🌐 The video is part of a Fast API tutorial series focusing on query parameters in web development.
- 🔍 Query parameters are additional tags placed at the end of a URL to enable more dynamic searching from the front end.
- 🛠 In Fast API, query parameters are included in function parameters as items not listed in the path parameters.
- 📝 The script demonstrates setting up query parameters with 'skip' and 'limit' to control the pagination of data retrieval.
- 📚 A fake items database is created for demonstration, with items like 'foo', 'bar', and 'bass'.
- 🔄 The script shows how to return a subset of the fake items database based on the 'skip' and 'limit' query parameters.
- 🔄 It's possible to make query parameters optional by setting default values, such as `optional_string = None`.
- 🔑 The video explains the distinction between path parameters and query parameters in Fast API and how Fast API handles them differently.
- 📌 With Python 3.10, the use of 'Optional' from 'typing' is no longer necessary; direct type hints like `str | None` are sufficient.
- 🔄 Pydantic's type conversion capabilities are highlighted, allowing for flexible input like 'true', '1', 'yes', or 'on' to be interpreted as boolean `True`.
- 🚫 The video points out a common Python error regarding the order of default and non-default parameters in function declarations.
Q & A
What is the main topic of this video tutorial?
-The main topic of this video tutorial is Query Parameters in Fast API.
What are query parameters in the context of Fast API?
-Query parameters are additional tags that can be included at the end of a URL to allow for more dynamic searching from the front end.
How are query parameters different from path parameters in Fast API?
-Query parameters are included in the function parameters and are not listed in the route path, whereas path parameters are declared in the route path and are used to look for specific segments in the URL.
What is the default value for the 'skip' and 'limit' query parameters in the example provided?
-The default value for 'skip' is 0, and for 'limit', it is 10.
How can you make a query parameter optional in Fast API?
-You can make a query parameter optional by setting its default value to None and using the typing.Optional annotation from the 'typing' module.
What is the purpose of using the 'short' boolean query parameter in the example?
-The 'short' boolean query parameter is used to determine whether to return a shortened version of the data or a more detailed version.
How does Fast API handle type conversion for query parameters?
-Fast API uses Pydantic for type conversion, which allows it to automatically convert string representations of query parameters into the specified data types, such as booleans or integers.
What is the error that occurs when non-default parameters are declared after default parameters in a function definition in Python?
-The error is that non-default parameters cannot follow default parameters in a function declaration, which is a generic Python error, not specific to Fast API.
Can you have required query parameters in Fast API?
-Yes, you can have required query parameters in Fast API, although it's considered unusual as required parameters are typically included as path parameters.
What will be the topic of the next video in the series?
-The next video in the series will cover request bodies, including submitting POST requests and sending data via POST and PUT methods.
Outlines
🔍 Introduction to Query Parameters in FastAPI
This paragraph introduces the concept of query parameters in FastAPI, explaining them as optional tags appended to the end of a URL to enable more dynamic searching from the front end. The tutorial demonstrates setting up query parameters in a FastAPI route by creating a fake 'items' database and using 'skip' and 'limit' parameters to control pagination. The default values for these parameters are set to 0 and 10, respectively, and the video illustrates how to modify the route to handle these parameters, showing examples of how to return different subsets of the fake database based on the query parameters provided.
🛠️ Making Query Parameters Optional and Type Conversion with Pydantic
The second paragraph delves into making query parameters optional and demonstrates type conversion using Pydantic in FastAPI. The tutorial modifies the 'get items' route to include an optional 'query' parameter and introduces the use of Python's typing.Optional for handling optional parameters. It also covers the simplified syntax available in Python 3.10 for optional parameters. The video further explains how to use Pydantic for type conversion, showing an example where a 'short' boolean query parameter can affect the response length, and how Pydantic automatically converts various string representations of boolean values to their boolean equivalents.
📚 Advanced Query Parameters and Handling Multiple Parameters
The final paragraph discusses advanced usage of query parameters, including handling multiple path and query parameters in a single route. The tutorial code snippet shows how to define a route with both required path parameters and optional query parameters, and how to update a response based on these parameters. It also touches on the proper order of default and non-default parameters in function declarations to avoid common Python errors. The paragraph concludes with an example of a required query parameter, illustrating how to enforce the presence of certain query parameters in a request and handle cases where they are missing.
Mindmap
Keywords
💡Query Parameters
💡Fast API
💡Path Parameter
💡Type Conversion
💡GET Request
💡Pagination
💡Optional Parameters
💡Pedantic
💡Boolean
💡Required Query Parameters
Highlights
Introduction to query parameters in FastAPI for dynamic searching from the front end.
Explanation of how to set up query parameters in a FastAPI route using function parameters.
Creating a fake items database for demonstration purposes.
Returning items from the database based on skip and limit query parameters.
Demonstration of how default query parameters affect the response.
Using query parameters to modify the behavior of an API endpoint.
Making query parameters optional with default values.
Introduction of path and query parameters in a single API endpoint.
Using Python 3.10's simplified type hinting for optional query parameters.
Type conversion with Pydantic for query parameters.
Handling different boolean values for query parameters.
Using query parameters to control the detail level of the API response.
Combining multiple path and query parameters in a single endpoint.
Error handling for non-default parameters following default parameters in Python function declarations.
Required query parameters and their impact on API requests.
Upcoming tutorial on request bodies and handling POST and PUT requests.
Transcripts
hello everyone and welcome to the third
video in our fast api tutorial series
uh in this video we are going to be
talking about
query parameters
as i mentioned in the last video uh
query parameters are just um any sort of
extra little
tags you want to put at the end of your
um your url
um they allow for you know a little bit
more dynamic uh searching
uh from the front end if you will
so let's go back into our
our running app that we have here we're
gonna modify the
oh no i don't have user i don't have
items anymore so let's
create an items route so we're going to
do app.get
items
and we're going to say async def
get
items or i think i called it before
list items
now
the way we had it set up before
if you had a path parameter
that you declared here
you then had to declare it here
and it would know to look for the path
parameter a query parameter
is an item that you're including in your
function parameters that is not
otherwise listed up here
that's it
so if we were to add in skip
we're going to call it an integer we're
going to by default set it equal to 0
and limit
integer and we're going to set it equal
to 10.
for this we're going to also let's just
create a
fake items
database
item name
foo
and we'll do a couple more of these
we'll call this one bar
and that one bass
okay
now
we're going to return
our fake items database
starting at skip
and going to skip
plus limit
and that's it
that's how we set up a set of query
parameters so if we go into here
items is just going to return everything
because by default
we're saying that the this integer is
going to be 0 so we're not going to skip
anything and by default this limit is
going to be 10. what is this saying
oh and watch i save it black is going to
yell at me yeah whatever it's fine
so if we were to add in something like
skip equals
2
then it would only return the last item
if we were to return
limit or do a query parameter limit
equals 1 it will return the first item
we go into here and we hit refresh
and we can see list items
and it doesn't give us any parameter
here it doesn't actually let us know
that there are
query parameters
but
you know you're just going to end up
having to open it up and find out
we can do the same thing that we did
before because it's a get request so we
can do limit of two
we're going to get foo and bar if we
start at skip of one
we would get bar and bass
okay so that's just a basic introduction
to
query parameters
now if we want to make some of these
parameters optional
what we can do let's do
app.get
items
item id
async
def
get item
item id
is a string
and the query is going to be a string
and let's do
optional
string
equals none and for this we need to from
typing import
optional
so now what we're going to do is we're
going to say if
the query so if it's not none
we're going to return
item
id is the item id
and the query
is the query
otherwise we're just going to return
item id
is item id
so this actually gets into um
when you want to have
path and query parameters
so you can see here we've got item id
and q
so fast api will know that item id is
actually going to be a path parameter
because we've declared it up here
it's going to know that q is a query
parameter because we're declaring it as
a primitive type
we'll get into um request body in the
next video um but if you pass something
in that's going to be a string or an
integer or a float boolean something
like that
then it's going to be a query parameter
the other thing that we can do is if
you're using python 3.10 you don't have
to use this optional notation anymore
you can just use str
or none
equals
none and then we can get rid of optional
here
so now if we refresh the page
let's close this up let's open this
so we have
this item id which is required
we're going to say
[Music]
hello
we're going to hit execute
and it only returned the item id
of hello
if we passed in a
query
let's do
world
and we hit this then we get the item id
is hello and the query is world so it
ended up going into this one
it's that simple um it's really not
terribly difficult to include um
optional uh
um
optional query parameters
okay um the next thing that we're gonna
touch on is type conversion we're using
pedantic
so let's see a neat little trick that we
can that we can include here so what
we're going to do is we're going to add
in an extra field
short we're going to call it a boolean
and by default it's going to be false
okay
what we want to do here now is we're
going to declare
item
equals
item id
item id
now what we're going to do here is we're
instead going to say
item.update and we're just going to
update with the query
if we have a query we're going to update
with the query
and then what we're going to do down
here is if not short
item dot update
description
and let's see can i do lorem 10
no it doesn't like it that's one
downside to uh
pie charm
more of ipsum let's go here
let's get
10 words
there we go
okay so if we're saying short is not
true
then we're gonna update the item with
this description
and then we're just gonna simply return
the item
okay
now we go back into here
and we refresh this page
and you can see we have now our item id
is again hello
we will again say world for this
and short can be either a boolean it can
be either true or false it's a boolean
so we pass this in
we see we didn't pass in anything so by
default it's assuming it's false
if we want to pass in this
then it works if we want to pass in this
then it works that's nothing interesting
the thing that is interesting is if
we're using it here in the url bar not
if we're using it here no one really
cares about this this is just for
testing
what we care about is using it
if we're fetching from a client-side app
so what we can do here
if we do items
and then we're going to slash
hello
and then we're going to say query equals
world
and then we're also going to say
short equals one
so what what pydantic did
is
it did type conversion of this integer
value
if we did short equals zero
i don't care about that then it returns
the long version with the lower mipsum
so that's another nice thing about
pedantic and about this the setup that
we have is it will be converted so we
can replace it with true
we can replace it with lowercase true
we can replace it with
on
or we can replace it with
yes
and all of those will work assuming that
those those convert
into
a situation where
true
where short equals true if we type in no
then we get
that value down there or we could just
pretty much get rid of it and we get the
same thing
okay so that's pretty much it for uh for
query parameters i mean there are a few
other things that we can do um we can
add in if we want to do app.get
we'll say users
user id
items
item id we can have multiple
path and query parameters async def get
user item
we'll say user id is an int item id is a
string
query is a string or none
which is none
and short is a boolean
which i'm going to leave it like this
and it's going to yell at me
we're going to see a non-default
parameter follow the default parameter
but let's just do
item equals
item id
item id
owner id
user id
and then if query again we're going to
update
query is query
if not short
and then we'll just
come up here we'll return this whole
thing again
i don't care about that go into the
terminal and we can see we got the error
here that we should have gotten that we
should have addressed up here
that's one other thing this is just a
this is not a fast api sort of situation
this is just a generic python situation
we're declaring a
default parameter here
you can't have non-default parameters
after default parameters in your
function declaration
so we're going to just declare that here
and everything should be fine
so we do this again
we
refresh this page and we can see here we
get all of these items here
um these path parameters are required
uh the query is not required we'll say
one two three four five six that can be
a string that's fine
and we're good
okay
um i think that's pretty much it we have
the ability to i'll just add one more
thing here
app.get
um
actually let me just see if it's up here
yeah i'll just add this one really
quickly
um
sample query
param we'll call it a string
and then we will say
sample query
param
uh this will just demonstrate that you
can have um required
uh query parameters
it's kind of a weird thing if you think
about it
um if you want something to be required
then you should just
in my mind you should just include it as
a path parameter but you can include uh
required query parameters so if we were
to type in one two three
hello and we will make short true
we return this
and you can see we get
that the request that it actually
submitted was this one here
so we'll copy this
we'll paste it here and let's get rid of
sample query param just to see what
happens
and you can see
we got field required
the sample query parameter variable was
required
okay
so now really i think that's it it's
about almost 14 minutes now
so in the next video we are going to
touch on request body like i mentioned
we have path parameters done we've done
query parameters now we're going to get
into the idea of submitting a post
request
and sending data via post put you know
something like that where it's not going
to be in the url but we're going to
actually pass data
back to the server
okay see in the next video
5.0 / 5 (0 votes)