Fast API Tutorial, Part 3: Query Parameters

JVP Design
2 May 202214:10

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

00:00

🔍 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.

05:02

🛠️ 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.

10:02

📚 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

Query parameters are a part of a URL that allow for the transmission of additional information to the server. In the context of the video, they are used to dynamically filter and paginate data requests. For example, the script discusses adding 'skip' and 'limit' as query parameters to control the range of data returned from a database of items.

💡Fast API

Fast API is a modern, fast web framework for building APIs with Python based on standard Python type hints. The video is part of a tutorial series on using Fast API to create web applications. The script demonstrates how to implement query parameters within Fast API routes to enhance data retrieval functionality.

💡Path Parameter

A path parameter is a part of the URL that is used to identify a specific resource. In the script, 'item id' is mentioned as a path parameter, indicating that it is a required piece of information in the URL to fetch a specific item from the database.

💡Type Conversion

Type conversion refers to the process of changing a value from one data type to another. The video explains how Pydantic, a data validation and settings management library used with Fast API, can automatically convert types. For instance, the script shows that the 'short' query parameter can be represented as an integer, a string, or a boolean, and Pydantic will interpret it correctly.

💡GET Request

A GET request is a method used in HTTP for retrieving data from a server at the specified resource. The video script discusses how to handle GET requests in Fast API, using query parameters to modify the data returned by the server, such as fetching items with specific 'skip' and 'limit' values.

💡Pagination

Pagination is the process of dividing a large set of data into smaller, manageable pieces or 'pages'. In the script, the concept is demonstrated by using 'skip' and 'limit' query parameters to control the pagination of items returned by an API endpoint.

💡Optional Parameters

Optional parameters are parameters that are not required for a function or method to execute but can be provided for additional functionality. The video explains how to make query parameters optional in Fast API by setting default values, such as 'optional string = None'.

💡Pedantic

Pedantic is likely a misspelling or mispronunciation of 'Pydantic' in the script. Pydantic is a library that enforces type hints at runtime, provides data validation, and offers more features than Python's built-in data validation. The video demonstrates Pydantic's capabilities in handling type conversion and validation of query parameters.

💡Boolean

A boolean is a data type that has only two possible values: True or False. In the script, the 'short' parameter is used as a boolean to determine whether to return a shortened version of the data. The video illustrates how different representations of true (like '1', 'true', 'yes', 'on') are accepted by Pydantic.

💡Required Query Parameters

Required query parameters are those that must be provided in the request for the server to process it. The script mentions that while it's unusual to have required query parameters, it is possible to enforce this in Fast API. An example is given where 'sample query param' must be included in the request.

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

play00:00

hello everyone and welcome to the third

play00:03

video in our fast api tutorial series

play00:06

uh in this video we are going to be

play00:09

talking about

play00:10

query parameters

play00:14

as i mentioned in the last video uh

play00:17

query parameters are just um any sort of

play00:22

extra little

play00:23

tags you want to put at the end of your

play00:25

um your url

play00:26

um they allow for you know a little bit

play00:28

more dynamic uh searching

play00:31

uh from the front end if you will

play00:34

so let's go back into our

play00:36

our running app that we have here we're

play00:38

gonna modify the

play00:40

oh no i don't have user i don't have

play00:41

items anymore so let's

play00:43

create an items route so we're going to

play00:45

do app.get

play00:47

items

play00:49

and we're going to say async def

play00:52

get

play00:53

items or i think i called it before

play00:55

list items

play00:57

now

play00:58

the way we had it set up before

play01:01

if you had a path parameter

play01:04

that you declared here

play01:06

you then had to declare it here

play01:08

and it would know to look for the path

play01:10

parameter a query parameter

play01:14

is an item that you're including in your

play01:16

function parameters that is not

play01:19

otherwise listed up here

play01:21

that's it

play01:22

so if we were to add in skip

play01:26

we're going to call it an integer we're

play01:27

going to by default set it equal to 0

play01:30

and limit

play01:32

integer and we're going to set it equal

play01:34

to 10.

play01:36

for this we're going to also let's just

play01:39

create a

play01:40

fake items

play01:42

database

play01:45

item name

play01:48

foo

play01:51

and we'll do a couple more of these

play01:56

we'll call this one bar

play02:01

and that one bass

play02:03

okay

play02:04

now

play02:06

we're going to return

play02:08

our fake items database

play02:10

starting at skip

play02:12

and going to skip

play02:14

plus limit

play02:18

and that's it

play02:19

that's how we set up a set of query

play02:22

parameters so if we go into here

play02:26

items is just going to return everything

play02:28

because by default

play02:30

we're saying that the this integer is

play02:32

going to be 0 so we're not going to skip

play02:34

anything and by default this limit is

play02:37

going to be 10. what is this saying

play02:43

oh and watch i save it black is going to

play02:45

yell at me yeah whatever it's fine

play02:47

so if we were to add in something like

play02:50

skip equals

play02:51

2

play02:52

then it would only return the last item

play02:55

if we were to return

play02:58

limit or do a query parameter limit

play03:00

equals 1 it will return the first item

play03:03

we go into here and we hit refresh

play03:06

and we can see list items

play03:08

and it doesn't give us any parameter

play03:09

here it doesn't actually let us know

play03:11

that there are

play03:13

query parameters

play03:14

but

play03:15

you know you're just going to end up

play03:16

having to open it up and find out

play03:18

we can do the same thing that we did

play03:19

before because it's a get request so we

play03:21

can do limit of two

play03:24

we're going to get foo and bar if we

play03:26

start at skip of one

play03:29

we would get bar and bass

play03:31

okay so that's just a basic introduction

play03:34

to

play03:36

query parameters

play03:37

now if we want to make some of these

play03:39

parameters optional

play03:41

what we can do let's do

play03:43

app.get

play03:46

items

play03:48

item id

play03:52

async

play03:53

def

play03:54

get item

play03:56

item id

play03:58

is a string

play03:59

and the query is going to be a string

play04:01

and let's do

play04:03

optional

play04:04

string

play04:05

equals none and for this we need to from

play04:08

typing import

play04:11

optional

play04:15

so now what we're going to do is we're

play04:17

going to say if

play04:18

the query so if it's not none

play04:21

we're going to return

play04:23

item

play04:25

id is the item id

play04:28

and the query

play04:30

is the query

play04:32

otherwise we're just going to return

play04:34

item id

play04:36

is item id

play04:40

so this actually gets into um

play04:44

when you want to have

play04:46

path and query parameters

play04:48

so you can see here we've got item id

play04:51

and q

play04:53

so fast api will know that item id is

play04:57

actually going to be a path parameter

play04:59

because we've declared it up here

play05:02

it's going to know that q is a query

play05:04

parameter because we're declaring it as

play05:06

a primitive type

play05:08

we'll get into um request body in the

play05:10

next video um but if you pass something

play05:12

in that's going to be a string or an

play05:14

integer or a float boolean something

play05:16

like that

play05:19

then it's going to be a query parameter

play05:24

the other thing that we can do is if

play05:26

you're using python 3.10 you don't have

play05:29

to use this optional notation anymore

play05:31

you can just use str

play05:34

or none

play05:35

equals

play05:36

none and then we can get rid of optional

play05:39

here

play05:41

so now if we refresh the page

play05:44

let's close this up let's open this

play05:47

so we have

play05:49

this item id which is required

play05:52

we're going to say

play05:53

[Music]

play05:55

hello

play05:56

we're going to hit execute

play05:58

and it only returned the item id

play06:01

of hello

play06:02

if we passed in a

play06:04

query

play06:07

let's do

play06:09

world

play06:11

and we hit this then we get the item id

play06:14

is hello and the query is world so it

play06:16

ended up going into this one

play06:18

it's that simple um it's really not

play06:20

terribly difficult to include um

play06:22

optional uh

play06:25

um

play06:25

optional query parameters

play06:29

okay um the next thing that we're gonna

play06:31

touch on is type conversion we're using

play06:34

pedantic

play06:35

so let's see a neat little trick that we

play06:37

can that we can include here so what

play06:39

we're going to do is we're going to add

play06:40

in an extra field

play06:42

short we're going to call it a boolean

play06:44

and by default it's going to be false

play06:47

okay

play06:49

what we want to do here now is we're

play06:51

going to declare

play06:52

item

play06:53

equals

play06:54

item id

play06:56

item id

play06:58

now what we're going to do here is we're

play07:00

instead going to say

play07:02

item.update and we're just going to

play07:04

update with the query

play07:08

if we have a query we're going to update

play07:09

with the query

play07:12

and then what we're going to do down

play07:13

here is if not short

play07:18

item dot update

play07:22

description

play07:25

and let's see can i do lorem 10

play07:28

no it doesn't like it that's one

play07:30

downside to uh

play07:32

pie charm

play07:35

more of ipsum let's go here

play07:39

let's get

play07:41

10 words

play07:44

there we go

play07:53

okay so if we're saying short is not

play07:56

true

play07:59

then we're gonna update the item with

play08:01

this description

play08:03

and then we're just gonna simply return

play08:04

the item

play08:07

okay

play08:08

now we go back into here

play08:10

and we refresh this page

play08:12

and you can see we have now our item id

play08:15

is again hello

play08:17

we will again say world for this

play08:20

and short can be either a boolean it can

play08:23

be either true or false it's a boolean

play08:25

so we pass this in

play08:28

we see we didn't pass in anything so by

play08:30

default it's assuming it's false

play08:33

if we want to pass in this

play08:34

then it works if we want to pass in this

play08:36

then it works that's nothing interesting

play08:39

the thing that is interesting is if

play08:40

we're using it here in the url bar not

play08:44

if we're using it here no one really

play08:45

cares about this this is just for

play08:46

testing

play08:48

what we care about is using it

play08:50

if we're fetching from a client-side app

play08:53

so what we can do here

play08:55

if we do items

play08:57

and then we're going to slash

play08:59

hello

play09:00

and then we're going to say query equals

play09:02

world

play09:03

and then we're also going to say

play09:06

short equals one

play09:10

so what what pydantic did

play09:12

is

play09:14

it did type conversion of this integer

play09:16

value

play09:17

if we did short equals zero

play09:20

i don't care about that then it returns

play09:22

the long version with the lower mipsum

play09:25

so that's another nice thing about

play09:27

pedantic and about this the setup that

play09:29

we have is it will be converted so we

play09:31

can replace it with true

play09:33

we can replace it with lowercase true

play09:37

we can replace it with

play09:39

on

play09:41

or we can replace it with

play09:43

yes

play09:45

and all of those will work assuming that

play09:47

those those convert

play09:49

into

play09:50

a situation where

play09:52

true

play09:54

where short equals true if we type in no

play09:57

then we get

play09:58

that value down there or we could just

play10:00

pretty much get rid of it and we get the

play10:02

same thing

play10:05

okay so that's pretty much it for uh for

play10:08

query parameters i mean there are a few

play10:10

other things that we can do um we can

play10:12

add in if we want to do app.get

play10:15

we'll say users

play10:17

user id

play10:19

items

play10:21

item id we can have multiple

play10:24

path and query parameters async def get

play10:28

user item

play10:29

we'll say user id is an int item id is a

play10:33

string

play10:35

query is a string or none

play10:39

which is none

play10:41

and short is a boolean

play10:44

which i'm going to leave it like this

play10:45

and it's going to yell at me

play10:48

we're going to see a non-default

play10:49

parameter follow the default parameter

play10:51

but let's just do

play10:52

item equals

play10:54

item id

play10:57

item id

play10:59

owner id

play11:01

user id

play11:03

and then if query again we're going to

play11:05

update

play11:09

query is query

play11:13

if not short

play11:16

and then we'll just

play11:18

come up here we'll return this whole

play11:20

thing again

play11:24

i don't care about that go into the

play11:26

terminal and we can see we got the error

play11:28

here that we should have gotten that we

play11:30

should have addressed up here

play11:32

that's one other thing this is just a

play11:33

this is not a fast api sort of situation

play11:36

this is just a generic python situation

play11:38

we're declaring a

play11:40

default parameter here

play11:42

you can't have non-default parameters

play11:45

after default parameters in your

play11:46

function declaration

play11:49

so we're going to just declare that here

play11:51

and everything should be fine

play11:54

so we do this again

play11:57

we

play11:58

refresh this page and we can see here we

play12:01

get all of these items here

play12:03

um these path parameters are required

play12:06

uh the query is not required we'll say

play12:10

one two three four five six that can be

play12:12

a string that's fine

play12:14

and we're good

play12:18

okay

play12:19

um i think that's pretty much it we have

play12:22

the ability to i'll just add one more

play12:24

thing here

play12:26

app.get

play12:28

um

play12:30

actually let me just see if it's up here

play12:32

yeah i'll just add this one really

play12:33

quickly

play12:34

um

play12:37

sample query

play12:39

param we'll call it a string

play12:43

and then we will say

play12:47

sample query

play12:49

param

play12:52

uh this will just demonstrate that you

play12:54

can have um required

play12:56

uh query parameters

play12:59

it's kind of a weird thing if you think

play13:01

about it

play13:02

um if you want something to be required

play13:04

then you should just

play13:07

in my mind you should just include it as

play13:09

a path parameter but you can include uh

play13:11

required query parameters so if we were

play13:13

to type in one two three

play13:16

hello and we will make short true

play13:19

we return this

play13:20

and you can see we get

play13:23

that the request that it actually

play13:24

submitted was this one here

play13:27

so we'll copy this

play13:29

we'll paste it here and let's get rid of

play13:30

sample query param just to see what

play13:32

happens

play13:34

and you can see

play13:35

we got field required

play13:38

the sample query parameter variable was

play13:40

required

play13:41

okay

play13:42

so now really i think that's it it's

play13:44

about almost 14 minutes now

play13:47

so in the next video we are going to

play13:49

touch on request body like i mentioned

play13:51

we have path parameters done we've done

play13:54

query parameters now we're going to get

play13:56

into the idea of submitting a post

play13:57

request

play13:58

and sending data via post put you know

play14:01

something like that where it's not going

play14:02

to be in the url but we're going to

play14:04

actually pass data

play14:05

back to the server

play14:07

okay see in the next video

Rate This

5.0 / 5 (0 votes)

Related Tags
FastAPIQuery ParametersWeb DevelopmentData RetrievalTutorialsAPI DesignDynamic SearchFront EndType ConversionOptional Parameters