Web Server Basics (Path & Query Params, Request Body, Headers) - FastAPI Beyond CRUD (Part 2)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everyone welcome back so now that we've installed fast API let us go ahead and create a simple web server so to begin let us create a new file and call it main. pii once we've created this file then we're going to go ahead and create our instance of our first API application so every first API application is going to have a main app instance that is going to to be the entry point to a first API application with this you get access to everything that you'll need to create your first API application but for us to create that instance then we shall have to first of all import the fast API class from Fast API so we're going to do that by saying from first API we are going to go ahead and import our first API and once we've been able to import the first API class now let's go ahead and create that with app so app is going to be a variable but this is going to be pointing to the F API instance or object once you've created that then we can pretty much get access to everything that we need if we want to create uh middleware if we want to create routes if you want to access HTTP methods all of those are going to be present within this app variable we've created so let us go ahead and create our first API endpoint or API path so an API point is the path on which you're going to make a request if we are to expect the response from this web server so to do that we're going to go ahead and use at app then we shall access a specific method such as get or post or patch or put or delete or any other HTTP method so these are the methods you can access on the app instance but what you want to do is to get access to an HTTP method in this case we are going to say get and this is going to require us to provide the path that we want to use that get method on so this case we're going to provide the root path and once we provide the root path now let us Define a function that's going to be triggered when we access that specific path so that is going to be a sync dep now notice that this is going to be an assing function and this assing function is what is called a qu routine but going to be one that's going to be called when we access that specific path or that specific endpoint so we shall Define this and let's say going to call this read uncore root which is going to be one for reading our root path and then we Define whatever code you want to be executed every time we access that specific endpoint so for our case we are simply going to go ahead and return dictionary and this dictionary is going to be a message of hello world so once this is done then our server is pretty much done so at this point we have a simple web server and to run it we're going to use the same fast API C that we introduced in the first video so for us to do that let us first of all explore some of the commands that are present on this first AP when you go within our first AP we can say fast API D- help and this is going to list like the manual for the first APA CLA so we now see that we have a variety of options and those are the version install completion show completion and so on but what you're interested in are the commands and we have basically two main commands the first one is going to be the dev command that's going to help us run our first API app in development mode and the second one is going to be the Run command that's going to help us to run our fast API app in production mode so development mode is one that's going to help us run our server in a way that's going to be in our development so meaning we can get things such as reloading of our server when we make changes and stuff like that well for the server there is where we go ahead and run our app in a way that's not going to reload and in a way that is similar to how we're going to run it when it is in production so that is what we are going to use but since we are in development we actually have to use first API Dev to run our server in development mode now if I run FP Dev this will go ahead and scan for some specific files and then run app but in case you do not want to do that then you have to specify the name of the specific module or of the specific package in which your app instance is going to be located for our case we have a name a main.py file but just in case we R this we automatically will get access to the app instance so F API has some files it will look at and it will see the app instance for example for our case is going to be present within our main.py so main.py and I think app.py are some of the files that it's going to scan through and it will automatically see the app instance but just in case it doesn't see that let's stop our Ser with control and C we shall now run our first API Dev but we have to specify the name of the module in which the app instance is located so in this case we have to provide mepy and when you run our Ser is going to to be run and the main app instance is also going to be imported so just like you see right here we shall get access to our main app instance and our API or our server is going to run and be exposed on Local Host 8000 or 127.0.0.1 H 8000 so let us try to access this uh this can be accessed by easily clicking control and click and that is going to go ahead and run our web browser right here so just like that we've successfully made our request and returned our response now that we've created our simple web server let us go ahead and Define more endpoints or more paths on our web server to help us return different responses so we're going to create an endpoint for greeting a user so what I'm going to do is to go right in here and I'll Define a new Endo so I'll say app dot get and in this case we shall Define the path to B one for GR but what we want to do is pass in a name that we want to pass to the server to grd so this is what is called a path parameter a path parameter is a variable that is dynamic that you may pass within your url as a way to send data to your server now this may be important in cases you want to perform an action is a specific resource on the server or you want to go ahead and search or you want to go ahead and do some sort of computation that you are passing this dynamically from your url so in this case for us to pass a variable within our path all we have to do is to use this bracket syntax and these brackets we provide the name of the variable that you want to pass to the server in this case we want to pass a name to the server through our URL so once you've been able to do that now let's go ahead and Define a function that's going to handle this request so you're going to say a sync death and this is going to be the Great Name function so this is going to take in a name and with fast we can Define the type of that specific variable that you want to pass within this path Handler function so you need to specify that this is going to be a string and you can also so specify the return type that is going to be returned with this request so in this case we want to return our Json which is going to be a dictionary once that is done now let's go ahead and return the greeting to the user so we shall simply do what we have done right here but in this case our message is going to be greeting the dynamic use app that has been passed in the URL which is our name so we're going to have a message and I'm going to use f strings so this is going to be hello and right here we shall provide world or the name so we shall provide the specific name that we are trying to Creet so if you have noticed we have been making our requests using our browser so if you go right to where we make this specific request can say 127.0.0.1 slgr and and in this case if we try to make this request we shall see that it's not found this is not found because it will require us to provide the name that you want to go ahead and pass the greeting to now when you go right here and we say SLG slash let's say Jonathan in this case we shall see that this is returning Jonathan so for now we are using our browser as our HTTP client to help us make requests to our server and with this we can pretty much do any sort of get request that you may want to pass to the server but in a real world scenario we may want to use an HTTP client that is going to make it easy for us to make these requests with the different HTTP methods and that is where we are going to choose our client so depending on your preference you may choose things like prman insomnia Cal but what I'm going to do is to use rest Fox which is a very lightweight open source tool for making these HTTP requests so I'm going to go ahead and open up my C and we shall look at how it works all right so this is my new rest Fox window and in rest Fox we simply have this minimalistic window and in there all we have to first do is to create a workspace so we can go to the add workspace part and when we create a new workspace we have to provide the workspaces name so let me just call this our first API Series so a workspace is simply where we're going to create our requests and in there we can choose the type of workspace I'm going to keep it to the default we can choose a path where I want that workspace to be so I'll just go ahead and select where I want that to be on our system and that will go ahead and create that in our new folder so when I go ahead and create we shall have our new workspace created right here now inside our workspace is where we can go ahead and create multiple requests we can also group them into folders and stuff like that so on this plus button right here we have options for creating a new request that's an HTTP request if we are creating one on a new socket we can create one for a web soet request we can create a new folder and we can also import other requests so let us Begin by creating a new request so we're going to call this the one for hello world so I'm going to go ahead and click create and once that is done now all we need to do is to go ahead and specify which URL you want to make that request too now I'll past what we have as our Local Host 8,000 and send and that will go ahead and make the request and return the response just like you see right here now the beauty about this is we can specify the request body if we are giving any query parameters can also do it right here we can specify any headers want to send with the request any authentication and so on so let's go ahead and do another request so I'm going to create a new request and that is going to be one to the great endpoint so on our great Endo we shall paste our URL right here and that is going to be on the slash path so shall provide our name let's say Jonathan and then this will go ahead and send the request and we shall get our response right here which is going to be hello Jonathan so if we said hello Peter that will be passing the query parameter Peter to our URL and that will go ahead and greet that specific user just like you see right here so from now on I'm going to be using this as a way to make HTTP requests to the server so now that we've looked at one way of sending data to our server let us look at other ways we can send data to our server for now we've been able to look at only path parameters which allow us to pass a variable or pass any input via our URL another way that fast API allows us to do this is through the use of query parameters you've probably come across places where you had to see a URL and then key value pairs of inputs being sent to the server so in this case we have this as G but this could be something like great question Mark and then name and then we can have something like Jonathan so this is what we call a query parameter it has the key which is going to be our name right here and equals then the value that that points to which is going to be Jonathan so let us look at how fast AP allows us to do something like that so we're going to head over back to our code and right here if you want to pass this name as a query parameter all we have to do is to go ahead and remove it from our URL so once we've been able to remove it within our URL we are going to keep it within our path Handler function as a parameter so first here is where is going to treat any parameter that is present within our path Handler function but not defined within our URL as a query parameter what I mean is if you go ahead and simply Define our URL without having to provide any path parameters but we go ahead and attach to that a path Handler function with many parameters then those are treated as query parameters so when we save our serve is now going to reload because we have Dave mode we go back to our client right here and we try to make this request so when you say slash greet we shall now see that we are getting an error now this error is what is called The unprocessable Entity error and what this does is to help us show validation errors that are being returned from first API now first API relies on pantic which is data validation tool that helps us to easily validate the kind of data that we pass through to our API or pass to our now in this case first AP is telling us that it it is expecting a name query parameter which we have not provided so this is the kind of response that we are getting let us go ahead and specify it within our URL so what we're going to do is to go right here and then use the question mark as the beginning of our query parameter we shall provide the key which is going to be our name and this is going to be let's say John Jonathan and that will be the one to return our name so if we send we're now going to see that our server is going to return the response hello Jonathan and it is doing this because we now have the query parameter name being the name Jonathan so if we change this to something like let's say Trevor we are now going to see that it's going to return Trevor because we have passed the query parameter of Trevor within our UR now this is a very important thing as it can be one way in which you can pass data to the API but this case you will be doing that via key value pairs now let us look at how we can mix the two so for now we've looked at how we can use path and query parameters and we've looked at how we can use them separately but what if we have a situation in which you want to use them within the same API endpoint so in here what going to do is to mix the two so we're going to be required to provide a path parameter and also a query parameter how are we going to do that so what I'm going to do is to provide this as slash grid and then I'll go ahead and provide the name as path parameter but in case you want to introduce a query parameter into this equation then you're going to remember that each parameter that we Define as part of our path Handler function is going to be a query parameter as long as we've not defined it within our URL so you can go ahead and provide another query parameter which is going to be our Edge and this is going to be an integer so when we provide this then we are going to go ahead and add this so I'll just say Edge and our Edge in this case is going to be our Edge so I provide this as our Edge so when I save what this is going to do is to require us to provide the name path parameter but we shall also provide a query parameter of age in that specific request so if we go back to our HTTP client right here we are going to have the name Trevor but when we send we are going to see not found so we have to provide this as a path parameter so we going to change this so we're going to have SLG grd slash Trevor and we shall also so when we send we see that it's going to require that age query par so when we do change that by providing the age query param so let's say the age is 23 if we send we shall now see that it's going to return the name as well as the age so this is how we can go ahead and mix both path and query parameters on the same API end point now that we've looked at how we can mix both path and query parameters let us look at how we can make query parameters okay optional in our example right here all we doing is to pass the path parameter of name and we then go ahead to greet the user with that specific name now let's imagine a scenario in which this name was an optional argument or an optional parameter that we passed to the server now removing it from the URL is going to make it a query parameter just like you see right here but let's say wanted to have a default value for the name that will be gred just in case we do not have a name specified now this is where optional query parameters come in to make our name parameter optional we're going to make use of a special class called the optional class that comes from Python's inbuilt typing module now P API allows for many inbuilt data types such as string int dict and so on to be passed as parameters but with it also it allows those that come from the inbuilt python typing module and we're going to look at how we can use most of those classes so to begin we're going to go ahead and import the optional class from typing so shall just come right here at the top and say from typing we are going to go ahead and import the optional class and once we've got the optional class now what we have here is a mandatory query parameter to make this optional all we have to do is to go ahead and pass it within our optional class so we we're going to rewrite this by saying that our name is going to be an optional string and this is going to now have a default value so to provide the default value to our string all we're going to do is to go ahead and provide and equal sign then we provide the default name that we're going to use for that specific name parameter so we're going to provide user as the name and what this will do is to go ahead and use the name name user in case we haven't specified the query parameter for name now notice that we are having an error here and this is happening because the H should also have uh to be first before this keyword parameter so for us to fix that we can also make sure that the name or the age has a default value so we can provide the default value being equal to zero what this means right here is the Ed is going to have a default value of zero in case we do not provide one and our optional name is going to have the value for user in case we do not have to provide the default value so I'm going to format this so that it looks a little bit better so I'm using black and what we have here is our formatted code but it is much more easier to read so we have an optional name parameter with a default value of user and an optional age or a qu parameter of age but it has a value of zero so if we go ahead and save and head over back to our client right here if we make this request we shall see detail not found now keep in mind that in this case we do not have query param or path parameters we do not have a path parameter for the name so if you go ahead and say slash grd in this case it's going to return hello user because we have a default value of the name as user and we also have our age as zero therefore it to return age as zero but in case we go ahead and provide this so we can go ahead and say user or actually that is going to be our name just like we see right here so if we go ahead and say name uh we can provide our name let's say Jonah and then that will go ahead and say not found because uh we have name Jonah this is going to be a query problem sorry for this so I have to provide the question mark right here so if we send this we are now going to see that it's going to return our name that is provided but just in case we leave out the name it's going to return user so when you provide the name it's going to return that name query parameter but in case we leave it out then iter to the default value of our user so let us also provide the Ed so to provide the age I'll just use the Ampersand and AG then let's say AG is equal to 23 so that will go ahead and return the age that we have specified within our query parameters and just like that we can be able to send optional values for query parameters just like we have done at this point we've only looked at how we can pass data to our server using path and query parameters we've also looked at how we can mix the two and how can make them optional but we are also going to have scenarios in which we are to send data to the server to create resources or to perform some action on the back end and this is where the request body comes in now the request body is a way we send data to the server that is going to be used and validated in some way so let us look at how we can be able to do that we're going to begin by defining an endpoint that is going to be creating some sort of resource and then returning it back to us so to do that we're going to first of all Begin by specifying that we're going to make a post request but keep in mind that a post request is not the only request that may send data to the server we may also have a post request that's going to update something on the server so when we do this so we are just simply going to say create or let's say book once that is done we shall Define the the Handler for this function so we shall say as sync Def and in this case we shall create book so let us go ahead and pass this for now so what we have done is to create the path which is create book and we are only going to access this via post request once we've been able to do that we have defined a function that's going to handle that specific request now one thing that we need to understand is when making a post request or any sort of request that involves sending data to the server then we are going to need some way of validating this data so to validate the data we are going to create what is a serialization model so a serialization model is one that's going to help us to change data from the database or change data from our server into something that any client that makes a request to our server can understand it can also be the r where we are actually getting data from a client and then sending that data to the server or making that data be in a form that the server can understand for our case what we're going to do is to create a model and this model is one that's going to help us to send data from our client validate whether that data is correct data and throw any validation errors in case we have some so to create a ptic model we are going to begin by importing the best model class and once you've been able to do that then all we're going to do is to begin by creating a class and this class is one that's going to define the data or the fields of the data that we want to send from our client to our server and vice versa so we're going to create this and let's just call it the book create model so this book create model is going to be a sub class it's going to inherit from the base model class and once it's has been once we have been able to create this class then we're going to define the fields that are going to exist on a book so we're going to have simple Fields such as the title of the book and this is going to be a string so we have to define the string using type hints so the syntax is just the field and then column then the type of that specific field so in this case we shall specify that this is going to be a string we can also have the author of the book and this author is going to be a string so once you have this then this is just enough for us to Define how we're going to send data to the server on our post request so to be able to do that then all we have to do is to go within our create book Handler function and then pass that as our data so we're going to Define this as our book create data or let's just say this is going to be our book data is the data that we're going to expect for this request and once we have that then we shall just say it's going to be of type B create model once you've been able to do that now let's go ahead and try to access that data so what you want to do is to just simply go ahead and return the information of that data that has been sent as a response so let us go ahead and return the title so our title in this case is going to be access from the book data or the data that was submitted when creating the book then dot so we shall access the title and then we can also go ahead and do the same thing for our author and this is going to be our author so our author is going to be access from the book data sorry for this and just like that shall be having access to our book author so let us go ahead and test this so I'll head over to our client right here I'll create a new request and I'll call this create book so for now we not having any sort of database but we shall look at that in the coming chapters so when you create a book we are going to specify that this is going to be a post request now I'm going to copy the URL that we have right here I'll close some of these and I'll paste it right here so you're going to access the slash create book endpoint so I'll say create Dash book and in this case if if we try to send the data we shall get an error same error that's going to be for unprocessable entity meaning that we are missing the request body so we have to provide the body so first here in this case is telling us that you know what you are trying to make a request on this end point but this requires for you to have a request body so let us go ahead and provide that now for us to provide a body we have to go to the body section of our rest Fox and in this case we have to provide the type of the body now we going to send the Json body so I just simply create a simple Json object and when I send when you send an empty Json object we shall see that there's some sort of validation on the back end that's going to tell us that we are missing the title and we also missing the author so let us go ahead and provide those if we come right in here and say that we are going to have the title our title is going to be let's say uh land jungle and our author is going to be S Jonathan so if we go ahead and send this shall now see that our response is going to be return so that's basically how we do it all you have to do is to go ahead and Define the type of data that you want to send to your server and then pass that as a parameter in your path Handler function and then you can go ahead and use the kind of data that you want to use for that specific request in addition to our request body and path and query parameters there may also be information about requests and responses that you may want to access and fast API allows us to do that in a very interesting way so when you head over back to our and right here every time we are making a request we are getting a response but the server is also returning some information about that specific response however we can also go ahead and specify information about the request that we are doing so for each of the requests that we are making right here the moment we are sending Json we are specifying that you know what server uh information is going to be sent with a content type that is going to be application SL Json we can also go ahead and specify many other headers so if we go back to our browser right here and we refresh uh we're going to notice that our response is going to be returned but I want to show you where the headers are being sent for that specific request if we head over to our browser tools right here and we go to the network section we can notice that when we refresh or make that request once again we can be able to know which type of headers are being sent on this specific request so let me make this a little bit bigger we can notice that all the headers are being sent right here and the request headers for this specific request include the accept so this is going to basically accept anything with text/html because this is returning an HTML page with this Json accept encoding so this is the particular encoding which is gzip and so on the host which is our local host 8,000 the user agent which is the specific browser that has made this request now in our case this is going to be this specific browser right here so all these headers can be accessed using fast API and let us look at how we can be able to do that now for us to access our headers we are going to create an API endpoint that is going to Simply return all these headers for a specific request now when you go back here going to create a request so let's just say slash and I'll just say this is going to be slash get headers and once we have this we can simply go ahead and say def get Dash headers and once we have this then we'll go ahead and have to specify all the headers that we want to access in this this specific part so let's go back to our browser right here all the headers that we have right here can be accessed using a header function that comes from first AP so the we access that is by first of all importing that function so we're going to go at the top and say from Fast API we are going to go ahead and import the header function and once we've imported the header function now we're going to go ahead and kind of use the same logic where we're going to just inject the parameter of that specific header into this specific path Handler function so let us start by looking at one so when you go back to our browser here we can see the accept header and this is one that we can access by using the lowercase accept So when you say accept uh this is going to stand for the accept header in our request for us to access this we can just simply say it's going to be a header and it's going to have a default value of n so what you have here is this is going to be a string but this string is going to be a header and in case this header does not exist then our request is going to return none so each of the headers that we can have for a request can be accessed using the lower case of that name so in this case this is going to be our accept header but we shall access it using the lowercase accept so when you try to return this we can say return or let's just say we can create a request headers dictionary and we are going to go ahead and set each value with the value of that specific header so we can now say request headers and in this case this is going to be our accept header and our accept header will have the value of the accept header that we get from our request so let's just simply go ahead and return our request headers as our response so if we try to do this we can go back to our client right here and in our client we are going to create a new request that is going to be for get headers and once we've been able to do that let us go ahead and provide the URL so I'm just simply going to get copy that I close that then we are going to go to local 8,000 SL get headers and when we send in this case we are going to see that this is going to be one to get all content type so this is going to be accept and then it's going to return the value of the that so let us see the kind of content type that we have for this specific request if we go back to our endpoint right here all we have to do is to just inject that as a parameter so we're just going to say content underscore type and this is going to still be a string and we shall access this as our header so if we come right here and provide this as our header we shall save and also set that as part of our request head as dictionary so shall just come and say this is going to be our content type sorry for this and our content type is going to be equal to our content tpe so once we've been able to set that up now let's go ahead and make that request and now we see that our content is going to be now so when you check the head for this request we do not see any type of content type being specified so if we go ahead and add our content type sorry for this so this going to be our content type and when you specify our content type to be application slash Json we shall now send our request and then this will get the content type header and then return it for our content type which is application stroke Json so let's try to get the user agent so the user agent is going to be the header that's going to be the string to represent who made that specific request so let us just try to fill that in if we come right here and say that we are going to get the user underscore agent so this is going to be the string and this will be the header shall be none so when you try to do the same thing we shall just set the key to be our user agent and the value of this is going to be the user agent so let's just set that up let's also do the same thing for the host so the host is going to be a string and this string is also going to be the same thing header and this will be none so we're going to do the same thing here we shall just say request headers and in this case shall specify our host and our host is going to be equal to our host so when you try to make this request once again again we shall now notice that it's going to return the user agent which is going to be this client which is rest Fox and if we return the host it's going to return our host which is Local Host 8,000 so for now we've seen how we can access the headers that are for this specific request and we have so far looked at how we can set up a simple web server we can pass path and query parameters and now we can also get our request headers we can also specify the specific status codes that are to be returned by a certain API endpoint the we do that is by going where we are specifying our request so just in case we wanted to customize this we can say that this is going to return a status code and then we can specify which specific status code now in our case this can be 200 so if I send this is going to return 200 but in case we wanted to let's say change this to let's say to1 then when you send this it's going to return to1 created meaning that our resource has been created on our website if wanted to customize it to make it let's say a 500 error still that's what is going to happen it's going to return a 500 internal server error so I hope you get the entire idea and this is how we create a simple web server using first a pi so we've looked at how we can create a simple web server we've looked at how we can run our server we've also looked at different concepts such as path query parameters how we can make them optional and how we can also access the headers for a specific request we've made to a specific API endpoint I hope you've enjoyed and learned from this video and if you've done so please consider supporting the channel by clicking the like button and sharing this video with whoever may find it helpful do not forget to subscribe to the channel if you're new and in case you want to donate to the channel I have buy me a coffee Link in the description and also I have a patreon on which I'm going to be releasing some of these videos thanks for watching and I'll see you in the next video where we're going to create a simple cred rest API
Info
Channel: Ssali Jonathan
Views: 750
Rating: undefined out of 5
Keywords: fastapi, fastapi tutorial, fastapi python, pass query parameters to fastapi, query parameters, fastapi params, fastapi path params, python fastapi, fastapi python project, restapi, fastapi query parameters, fastapi path parameters, fastapi example, fastapi project, fastapi course, path params in rest, fastapi get using path parameters
Id: 7DQEQPlBNVM
Channel Id: undefined
Length: 42min 53sec (2573 seconds)
Published: Wed May 29 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.