Python FAST API Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everybody and welcome to another youtube video so in today's video i'm gonna be showing you the python web framework known as fast api now as the name suggests what this web framework lets you do is create apis in python the reason it's named fast api is because you can make apis very very quickly in fact we can write our first api in about four or five lines of code and then these apis are very quick themselves they have very high performance with that said this video is not designed for absolute beginners you should have some knowledge with python however i will explain to you what an api is i'll talk about the common api kind of method so get post uh put patch update all of those kind of ones and i will discuss json and just kind of how an api works if you're unfamiliar with apis don't worry but you should have some knowledge of python to be able to follow along so that said let's dive in after a quick word from our sponsor before we get started i need to thank intel for sponsoring this video and having me talk to you about their openvino toolkit and the intel dev cloud for the edge the openvino toolkit is free software that helps developers and data scientists speed up computer vision and ai workloads streamline deep learning inference and deployments and enable heterogeneous execution across intel's platform from edge to cloud on the openvino website you can find free resources like a tutorial on how to perform a style transfer using a deep learning model and a cheat sheet containing everything you need to know to get your ai application up and running as fast as possible if you want to get started with the openvino toolkit you can use intel dev cloud for the edge this is a cloud-based development sandbox that gives developers access to the latest intel edge hardware and software to build test and prototype their ai applications with these technologies and resources you can build optimize and deploy your applications with ease start building your ai and machine learning applications today by clicking the link in the description and taking advantage of the openvino toolkit thanks again to intel for sponsoring this video alright so as we enter the video here the first thing i'll mention is that there is timestamps linked below if you want to skip to a certain part in the video or you want to kind of skip through the more beginner explanations maybe if you're more advanced regardless i'm going to start here by discussing kind of the core advantages of fast api and why you may actually want to use it so fast api is very fast to make an api with right the name is very fitting and one of the reasons for that is that when you create an api in fast api you're actually going to be defining the types of all of the data that your api is expecting so traditionally when you write an api or some web framework or something or web app whatever in python you don't actually explicitly set what type all of the information that your endpoints so kind of a url on the server are going to be accepting now what that means is you have to do a ton of data validation you have to check to ensure that you know you actually got an integer you got a stringer you got some json object or something like that and while this is kind of a lot of grunt work and you're just writing a ton of stuff to essentially check that the information that was sent to your api is correct now in fast api all of this is actually automatically done for you so if someone sends the wrong piece or wrong type of information to your api endpoint it will automatically return to them kind of an error message saying hey you know this was supposed to be an integer and i got a string whatever but that's kind of the first main advantage of fast api is it does all of this data validation for you because when you create endpoints with fast api you're going to define explicitly what type all of the information that's going to be past that endpoint will be so whether that's a path parameter a query parameter or actually the kind of uh request body you're going to define exactly what that should look like so fast api can automatically handle the data validation next thing that's great about fast api is that it auto documents your entire api so since you are actually giving all of the types for what's expected for the api fast api can automatically generate documentation that also works as kind of like a test script so i'll show you this in a second but it actually generates a web page that you or maybe your front end engineer if someone else is working on this could go to to see all the api endpoints and exactly what they expect and any description or information that you would have provided for them and then last thing since you're defining the types of all of these kind of all this information related to the endpoints you're gonna get really good auto completion so if you're working in an actual ide like vs code or pycharm i'm not doing that right here i'm in sublime text then you get really good auto completion and just better completions that you would typically have because of the fact you're defining these types so anyways enough talking let's get into it the first thing we need to do is install fast api so if you're on windows open up command prompt if you are on mac or linux open up terminal and you're going to type the following command pip install fast api to install the fast api module if for some reason this doesn't work for you try the following command you can see i already have this uh requirement satisfied try pip 3 install fast api if that doesn't work for you try python hyphen m pip install fast api if that doesn't work for you try python 3 hyphen m pip install if none of those work for you then go to the links in the description i'll have a video for mac and a video for windows showing you how to fix this command now once we've installed fast api i'm going to assume you've done that at this point we're going to install something called uv corn now this is what we're actually going to use to run our api kind of as like a web server which you'll see in a minute but regardless you need uv core as well again if this command doesn't work try those sequences pip 3 python m so on and so forth all right so we can leave the command prompt open we'll be using that later then what we need to do is open up a python file in some editor for me i'm working in some directory this on my desktop it's called fast api you can kind of see it at the top left hand corner of my screen for the path for this file i just have a python file called working.pi obviously place yours wherever you want name it whatever you want but make sure you know where it is because you are going to have to kind of access that all right so now what we're going to do is make sure our fast api installation is working so we're just going to import fast api save our script run it i'm running mine with ctrl b in sublime text and you can see that we got no errors and so we're all good fast api is installed so now we're going to write kind of our first api i'll go through this fairly quickly just showing you how to set this up and then i'll kind of walk through each line and discuss what i did so i'm going to say from fast api import and then make sure you look at the capitalization here fast api this is the first thing we need to do we're going to import this fast api class module whatever and then we're going to say app is equal to and then fast api with an open parenthesis and a closing parenthesis what this will do is creates kind of i guess like let's say an api object something that's going to initialize our api and say okay this app variable right here this is telling us we just created our first fast api regardless is what you always need to do when you are starting uh working with fast api okay so now that we have this we can create an end point and at this point in time i'm going to stop for a second quickly discuss what an end point is so if you hear me say endpoint or root or route or whatever what that really means is something like slash hello slash you know get hyphen item so when when you're talking about an endpoint you have a kind of base server url in our case our base url is going to be localhost because we're not distributing this app we're kind of i guess deploying this app we're just hosting it on our local machine so the base url would be localhost and then the endpoint would be slash hello and so you have all of these different endpoints and when you go to these different endpoints well different stuff happens right different information will be sent back to you maybe you're sending information to an endpoint but regardless that's what i mean by endpoint slash something essentially right it's kind of like the ending path after the main domain so if you were looking at you know like facebook.com an endpoint would be like slash home right that would be one of the endpoints for facebook.com regardless that's an endpoint so to create an endpoint what you do is you say app dot and then the method that this endpoint is going to kind of accept or that is going to be so when we talk about http hyper text transfer protocol i believe that's what that stands for at least we have some main different methods so whenever you set up an endpoint you can set it up to kind of be a different method if that makes sense i'm having trouble coming up with the exact word for it but the idea is we have these kind of core http methods and they all mean something different now one of the main ones is get we have post we have put and then we have delete and we have a few other ones as well but these are kind of the four core ones now when you set up a get request or you have an endpoint that has a get method what this means is that this endpoint is going to be returning information that's kind of all it's doing is you're asking this endpoint to get something for you and return it to you that's kind of the get http method now when we talk about post this actually means that you're going to be sending information to the post endpoint or this end point here that is method post will be creating something new whenever you're creating data kind of adding something to the database you're doing this with a post request so you would be maybe posting a new user login or something right or a new user sign up right you would post that to an endpoint because you're going to create a new user in the database because they just registered or signed up or whatever and then put this is to actually update something that's already existing in the database just you know kind of modify information essentially and then delete well that's straightforward you're deleting something getting rid of information now of course there's a few more but these are the core ones the ones that i'll show you so depending on the method you want your endpoint to be you're going to say app dot and then the method so in this case i'm going to go with get and then you're going to put the end point right here so i'm going to say slash and make sure sorry before the app you put this at symbol right here i'll discuss why we need that in a second so for now i'm going to set up what i'm going to call my home endpoint and what this is going to do is just return some data that says test so what i've just done is i've said at app.get i've defined my kind of root or endpoint as slash i've then created a function i've called this home make sure that your kind of root or endpoint is right above the function that will be triggered when you go to this root and then what you're going to do is return some python dictionary this will be kind of the data or the information that's going to be returned when you go to this endpoint so hopefully that kind of makes sense but if we go to slash now once we kind of run this web server what will happen is the information data with the key test will be returned so this is how you kind of set up a root you say at app dot whatever the method is again the root you define a function right underneath it you can name this function whatever you want and then you return some information okay there we go so let me just show you how we can run this then i'll talk about what's known as json and kind of what an api is and actually how that works so what i'm going to do here is go to my command prompt and i need to change directories into the folder or into the directory where my python script is so in this case i'm on windows i'm starting in my home folder so i'm going to go to cd desktop and then i'm going to cd into fast api then what i'm going to say is uv cord this is the thing we just installed and i'm going to say the name of my file which is working notice i'm not adding the dot pi you don't want the dot pi so make sure you don't have that and then oops what did i just do here okay i've messed up my cursor somehow anyways uv corn working colon you're gonna then say app app being the name of the variable that you have fast api stored in and then space hyphen hyphen reload now what this hyphen hyphen reload will do is tell uvcorn to constantly reload the web server every single time you make a change to the python file that's kind of storing the api so uvcorn the name of your python file mine is working notice i don't have the dot pi extension then the name of the variable storing fast api colon colon or sorry hyphen hyphen reload and then press enter and you should see that it says application startup complete and it shows you the url right here that you need to go to to access this website or access this api sorry so in this case it's http colon 127.0.0.1 colon 8000 pretty much the same thing as localhost so what i'm going to do now is go to my browser and say http slash 127.0.0 colon8000 and i'm not going to go to the docs page quite yet and here you can see that we get this data saying test because we went to the slash endpoint so when you just put slash that means if you go to any endpoint essentially on the server like if you go to just the default one so you don't have anything after then it's going to return or uh treat it as if you're at this endpoint so i think i think you guys get what i'm saying i'm kind of mumbling around here but the point is that like this just that is equivalent to the endpoint slash regardless you can see we're getting data test so now let's do a quick change this i'm going to say testing i'm going to save that now i'm going to go here and refresh and notice it says testing that means our reloading is kind of working great now what you guys saw i accidentally loaded this docs page so we might as well just go to it right now if you go to your uh server url which is just 127.001 colony thousand then slash docs it will have automatically generated documentation for your api so at this point we only have one endpoint it is slash the function name is home right so that's why it's saying home and then if you press on this it says okay it doesn't take any parameters and what is it if we try it out so we can try it out by pressing that button and press execute we can kind of see the sample response body we can see the request that we sent to get this response this is a way that you can actually test your api from this docs page right here alright so i'm going to quickly discuss what an api is so an api stands for application programming interface and really what an api is is some web service that provides an interface to applications to manipulate and retrieve information so if we're talking about something like amazon amazon almost definitely i don't know the internal makeup of amazon but almost definitely has an api now they probably have multiple apis but one of their apis may be responsible for handling their kind of inventory system right figuring out what items are in stock what items are not in stock how many items are in stock how much they cost whatever we can think of a common api that amazon may have as an inventory api now this api here is separate from the different front ends that display this information so if you're talking about amazon they have a web app right they have a mobile application they have something that works on like alexa or google home or whatever they have all of these different services that all rely on the same underlying information they need to know inventory they need to know what's in stock and so rather than writing you know five inventory management systems they would write one in the form of an api application programming interface and now any of their applications that are used by users can access this same information by sending requests to the api so when you go to the you know website and you look up i don't know let's say graphics card right none of those are in stock right now what's going to happen is there will be a request that is sent to the amazon api that says hey i'm looking for graphics cards right and then it will return all of this information to the front end and display all of that for you and then when you click on a specific graphics card it will then say oh i need all of the information related to this graphics card again a request will be sent to the api the api will then send all of that information to the front and so hopefully that gives you an idea of kind of how the communication works but the same thing that happens on the mobile app right it sends a request to the api and this way you don't need like five different backends to handle every single one of your applications and all of their information you have one api responsible for kind of distributing and giving you all of the information that you need and this is just good practice whenever you're kind of writing code it's a very good idea to separate your front end and your back end so if at any point in time you want to create a different kind of representation of your data on the front end you can just use the same api and the only thing you need to change is kind of the way that you're displaying so hopefully that gives you an idea of what an api is and kind of how that works now i don't know the internal makeup of amazon's web services and all of that kind of stuff so that could be completely wrong what i described but that's like an example of where an api might make sense to use with that said what i need to quickly talk about is the data that apis kind of exchange or that i guess anything over http really exchanges so right here we returned a python dictionary now this python dictionary is actually automatically converted to something known as a json javascript object notation as soon as it is returned from this function so fast api actually handles jsonifying all of our information so we can work with strictly python types in our actual api now this might seem a little confusing but whenever you are returning information from an endpoint it's kind of standard that that information is in the format of json now you don't really have to know what json is or what it looks like it's just a little bit of a different syntax than kind of a standard python dictionary and well you can just understand here that a fast api any data that you return from your endpoints is automatically converted to json and so whoever receives it on the other end may have data that looks a little bit different than what you returned just because it's all going to be converted from kind of vanilla python types to this json format now same thing when these endpoints are receiving information whenever they get like maybe a query parameter they get some request body that will come in as json and be converted into vanilla python types so we don't need to worry about kind of dj sonifying or jsonifying all of our data just make sure you understand that all of the data exchange kind of between apis is in the format of json we're just lucky here that fast api can convert all of this to kind of vanilla python types for us anyways that was a lot of talking i hope i didn't bore you guys too much with that but if you guys are beginners hopefully that helped you out let me know in the comments now let's continue working here and let's create a few more endpoints so i'm going to make a new endpoint here i'm going to say app.get and let's make this slash about now what this is going to do i'm going to say define about and oops if i can type about properly and here i'm going to just return some data and i will return is data and about just so that we have another endpoint so we can see kind of how this works when we look at the auto documentation so now my web server should have refreshed if i go to docs now notice i have another endpoint called about right and if i press on this i can press try it out i can press execute and when i execute that notice that we get our data we get about now same thing here if i go to slash about we can see that we have data about awesome so that is kind of two examples of using an endpoint that has the get method now we also can use an endpoint that has the post method the patch method and the delete method but before we do that i want to show you something known as path parameters and query parameters and to do that we're going to kind of get into our first example here so i want to treat this api that we're creating as kind of an inventory management system like the example i gave you from amazon so i'm going to say inventory i think i spoke that correctly is equal to and we're going to make this a dictionary now inside of here we're going to store a bunch of different like stock right all of the different items that we may have in stock and all of these items will have a unique id so the key in this dictionary will be their id so i'm going to say you know item with id1 the name of this item is a let's just say milk maybe we'll treat this like a grocery store or something the price of this item is i don't know how much is milk let's say 3.99 and we will say maybe the expiry uh this could be actually i don't want to do like a date time thing right now let's do something else milk maybe we'll just say brand and actually i don't even know like a milk brand we'll just say uh regular now of course there could be a lot more information we're just kind of doing this simply for now because we don't need to go into anything like crazy advanced okay regardless we have name we have price we have brand and then we have an id for this item so what i'm going to do is set up an endpoint that can retrieve for us item information based on its id so what i'm going to do is say at app.get this is going to be a get method for this endpoint i'm going to say get hyphen item and then what i want is the user to actually pass me some id for this item and so what i'm going to do is put inside of curly braces item underscore id now what this means when i do this is that whatever is here could be anything right this item id could literally be anything and based on what this item id is i'm going to return something different from this endpoint so now i'm going to say define get underscore item and now what i need to do is define a variable to represent this item id so i'm going to say item underscore id needs to match the name here colon int now what this is is a type hint in python whenever you do a colon beside a parameter and then you define the type it's known as a type hint and the reason we do this in fast api is to tell fast api that this item id is supposed to be an integer so if you try to pass something that is not an integer to this endpoint for the item id it will automatically return to you we don't have to do this fast api will automatically return an error message saying hey this wasn't an integer it needs to be an integer and i'll show you how that works but this is our first example of what's known as a path parameter so now what i'm going to do is just return and i'm going to return my inventory at the item underscore id so let's just go ahead and have a look at this and see how this works i'm going to go to now the end point slash and this was get hyphen item and then slash one now when i do that notice it gives me all of the information relating to that item so i have the name which is milk price 399 brand regular awesome but now if i try to go to something that is 2 we get an internal server error the reason we get that is there is no item with id2 and so this line right here cause an error i'll show you how we fixed that after but just want to show you that and then finally if i try to do something like go to milk notice that we get this detailed error message saying hey this value is not a valid integer you need to give us a valid integer and even tells us the item id is the thing that is incorrect and so that is how you set up a kind of path parameter now you can also set up multiple path parameters maybe we have items that have the same id or maybe we just want some more information from this user this example is going to make too much sense but i'll just show you how this works we can take an item id and we can take something like i don't know maybe a name right now that we have this name here we would need to go inside of our uh what do you call it uh parameters here and define name colon string saying that okay this name right here this is expected to be a string and then what we could simply do is we could return inventory item id and maybe we could add something to this i'm trying to think how it would do this i can say dot update and actually no this isn't going to quite work uh there's not really a way for me to return the name string that's going to make sense so anyways i just want to show you we could take multiple path parameters so now if i go here and i refresh this so let's go get item 1 slash test notice that this still works this is totally fine we took another path parameter in and well all is good so hopefully that kind of makes sense but this is how you take multiple path parameters inside of your kind of endpoint all right so sorry for the abrupt cut i had some issue with my editing software anyways what i'm going to show you now is how we can add some more detail to our path parameters so i'm going to remove name because we don't really want this one anymore so i'll get rid of this from the actual parameters and now what i'm going to show you is something known as path so we're going to import this function called path and what we can do is set our item id colon int equal to and then this path kind of function right here now what this is going to do is allow us to add some more detail or kind of some more enforcement or constraints on our actual path parameter so for example if i wanted to add a description to this path parameter to tell the user what this actually is like the information they should pass for item id i could say something like description is equal to and then i can write a description and for my description i'll just say the id of the item you'd like to view okay and then one thing here before i do description i always need to give a default value for this so i'm going to say none and then description the id of the item you'd like to view now i understand this might look a little bit weird but whenever you use these type of functions inside of the parameters for an endpoint you always have to start with the default value for this parameter so if item id wasn't passed what should this default to in this case it's going to default to none so if you don't pass an item id by default it will be none however you'll see since we're talking about path parameters here it is actually required that you pass an item id so we will never end up using the default value i know this might be a little bit confusing this will make more sense once we move on to the next thing which is the query parameters which can be optional regardless i'm going to put none here i'm going to say description equals the id of the item you'd like to view now if i go back here and let's just refresh this so get item one you can see all is good and if now i go to my docs you can see that says get item item id and notice that now there's actually a description it says the id of the item you'd like to view because we added that description inside of this kind of path thing right here now what we can also do is have some constraints on item id to make sure it's say greater than one or greater than some value so what i'm going to do is say gt this stands for greater than and then i'm going to say this is equal to and make it equal to zero so now what this is saying is okay this item id must be greater than zero now another few ones you can use here is lt that stands for less than that means this must be less than zero you can do l e that's less than or equal to and then you can do ge that's greater than or equal to and you can do kind of any combination of them so i could do maybe uh let's say g t zero and lt equals two so now the only valid thing you can pass is an id of one if you pass anything else you're going to get an error so let's test this out let's first just refresh this here and i don't think it actually tells me the greater than like enforcement here but if i go to slash get hyphen item slash two notice we get a problem it says message and sure this value is less than two right because uh this did not meet the less than constraint now if i do one all is good and if i try to do zero we get an error here saying no this is not valid make sure this number is greater than zero hopefully that makes sense but that is kind of the basics of using this path thing right here okay so now we've talked about path parameters the next thing to talk about is query parameters so a query parameter is something that comes after the question mark in a url so sometimes you'll see something like i don't know maybe let's go facebook.com and then some endpoint slash home and then there's something like question mark and it says like you know key equals whatever it says like redirect equals and then maybe some page and the thing is this is what's known as a query parameter so whenever you have a question mark and then you have some variable name equals and then some value this is a query parameter and you can have multiple of them let's just make the redirect like slash tim and then we would do an ampersand and then we would say you know msg equals fit and now we have two query parameters redirect which is equal to sim and msg which is equal to fail so how do we accept query parameters for our endpoint so i'm going to make a new endpoint here and show you how we do this i'm going to say app.get and i will make this get by name get by colon name and what this is going to accept is one query parameter and this query parameter is going to be the name of the item that we want to kind of retrieve and so what i'm going to do here is say name colon str now what this is saying is okay we are going to accept one query parameter named name so by default if it does not see this variable that you've defined as a parameter in the path to the endpoint it will by default be a query parameter so this means we are looking to accept a parameter called name which is equal to a string so i'll show you how this works but that's kind of what this means and now what we would need to do inside of here is we need to look through our inventory and find something that has the name of whatever the name is that it was passed so what i'm going to do is make a for loop here i'm going to say 4 item in inventory and actually this should be 4 id in inventory actually i can't call it id i'll call it item underscore id i'll say for item id in inventory if inventory at item underscore id at name is equal to the name then what we will do is return inventory at item underscore id otherwise so if we get to the end of this and that doesn't work we'll return something that says data not found okay so now we've created an endpoint it's taking one query parameter named name so let me show you how we would actually call this endpoint so if i go here now and i change this to be get what do we call this get by name so get by hyphen name and then i do a question mark and i say name is equal to and then milk notice that this works and we get the item that has the name milk now if i make this equal to something else i say name equals tim we get data not found because well there is no inventory item that has the name tim now if we don't pass any query parameter and we just do this it's telling us hey this field is required we need a query parameter you can't call this endpoint unless you have this query parameter name and we can add multiple query parameters as well we could add like price we could add a brand whatever if we wanted to do that and so anyways now let me show you how we can add more detail to our query parameters and how we can make them potentially optional so right now we put name in here it's equal to a string and this by default is a required query parameter but maybe we don't want this to be required maybe we want it so that you can call this endpoint without this query parameter in that case we would simply set this equal to none and now what this means is since this has a default value this query parameter is no longer required it automatically becomes optional so if i save this now and i go back and i just run this notice that this works we don't get an error anymore because now this query parameter name is strictly optional we can pass it but we don't have to and by the way it's recommended from the fast api docs that you do the following when you have an optional parameter you say from and typing import and then you're going to import optional and then you make this type here optional string now you don't have to do this you saw that this worked when we didn't do this but this is just going to give better auto completion for your editor when you decide to do this so optional is strictly for like yourself like the developer it just makes it easier to get better autocomplete when you're writing code here you do optional string to note that yes this parameter here name is indeed optional so if i run this you'll see when i save this this still works this is totally fine okay so hopefully that's clear that's how you do a query parameter just to show you quickly we could do another query parameter i could say let's just make this one test maybe this would be an int and maybe we want this one to be mandatory you do have to pass test so now that i've done this this means that if i refresh this now let me go here and just just hit enter oh what is this name string non-default argument falls ah okay it's actually a good error to run into let me discuss this so we just got an error here saying that a non-default argument came after a default argument so for fast api it does not matter the order in which you kind of write out these different parameters so it doesn't matter if you have like you know item id first or if you have name first if you have test first fast api will be able to figure it out doesn't matter what order you put it in however for python it actually gets kind of mad when you put something that's not or put something that is mandatory after something that's not mandatory and so the way to fix this is to well you could reorder this put test first when i say that i mean we could do test like that or what we can do is simply add an asterisk like this and then do a comma now if we do this everything will work essentially this is uh it's kind of hard to explain exactly what this does but this says okay let this function accept unlimited keyword arguments or unlimited sorry positional arguments and then the rest of them should be treated as keyword arguments i'm not really going to explain why that works but if you get some error saying hey you know your parameters are all ordered wrong just put an asterisk first and then this will fix it for you so if i go here and i refresh this now you can see it says field required we're looking for oops get by name message field required type query test okay sorry i'm just trying to decipher that so now it's all working but if i now say test is equal to 2 you can see we're all good because we passed the mandatory keyword argument and i can pass another keyword argument say name is equal to milk if i do this correctly press enter and uh what is it message value is not oh sorry this needs to be an ampersand not a question mark so let me try to fix this ampersand okay and now we're good now we get the item milk okay hopefully that's clear that kind of covers the uh what do you call it keyword arguments or sorry not keyword arguments query yes query parameters that's what it's called now let me just show you how we can combine query parameters and path parameters together so let's say get item by name we wanted to accept a path parameter as well as a few query parameters maybe we wanted the item id and we wanted the name i don't know why you'd want that but maybe you do so in this case we can say item underscore id and now what we need to do is make sure we have a variable called item id that is inside of the get name parameter it doesn't matter where we put it i'm just going to put it first i'm going to say item id colon int and now this will work we can now accept our item id as a path parameter our name as an optional keyword sorry optional query parameter and then test as a mandatory query param so now if i do this and i go here and i refresh we get not found but if i go slash one slash and then question mark notice this works right we're all good and yeah that's that's fine so hopefully that kind of illustrated to you how that works but that is how you can combine path arguments and query arguments okay so now that we've looked at query and path parameters we're going to move on and talk about the request body so oftentimes especially when you're trying to kind of add information to a database you're not going to be sending all of this information in query parameters or path parameters you're going to be sending like a bunch of information as what's known as the request body so i'm going to set up an endpoint here i'm going to say at app.post so a new method this time i'm going to say slash create item now what we're going to do is kind of change this a little bit so that we are now going to have an endpoint that allows us to create a new item in the database so i'm going to say define create underscore item and what i want to accept here is a request body i want some information relating to the item so i want the name of the item the price of the item and potentially like the brand of the item as well and so what i'm going to do here is say item and this is going to be equal to a type that we haven't defined yet which is called item so whenever i'm looking for a request body so i want something that is not a query parameter and i want something that's not a path parameter i need to set it equal to a class that inherits from something known as base model now i'll kind of discuss this in more depth in a second but we're going to go up to the top of our program and say from pi dantic import base model now what i can do is create a class i'm going to say class item this inherits from base model and i can now define in this class the kind of structure of the data that i am looking to accept as this item parameter right here for create item so i'm going to say well i want a name this is of type string i also want a price this is of type float and then what else do i want well i want a brand and this is going to be optional because i don't know if i i'm going to take a brand every time string equal to none so just like it worked for the query parameters and the path parameters if you want to make it optional you can add this kind of optional thing that's not required but it's good practice and then make it equal to none or make it equal to some default value and that now makes brand optional awesome so now that we have that i'm going to save this and what this can do uh let me actually just go here and let me just return kind of an empty dictionary for now just so we can see how this works but since this is equal to this class right this is now telling fast api that okay this is for the request body this isn't a query parameter so it's not expecting me to do something like question mark item equals and then type it all out it knows that i'm going to be sending this item information in the request body okay so i'm just going to go here and refresh this and let's go and see if if something went wrong okay looks like everything is good so now if we're looking at our documentation we see we have this new endpoint called create item so look it says that the request body is required we look for a name a price and a brand uh and if we wanted to try this out we could although right now it's not really going to work it's not going to do anything although if i press try it out and i i just i can just send this and i press execute notice that we're just getting kind of an empty response because we haven't typed anything out so what i want to do now though is i want to take this item and i want to actually insert it into the inventory and what i can do is rather than like trying to create a structure that looks like this i can just insert this actual item itself which you'll see in one second so what i'm going to do here is now change create item so it also accepts an id so i want an item underscore id the reason i want an item id is because if i'm going to insert this item well i need an id associated with it so now i also need an item id here so i'm going to say item id colon int now this is going to be assumed to be a path parameter because it's in the path right so we have our item for the request body and we have our item id that is a path parameter awesome so now the first thing i'm going to do is check to see if this item id already exists i'm going to say if item id is in and then this would be inventory let's go here then what i want to do is just return and we'll say error item already exists or item id already exists great now if that's not the case we can just add this item into uh the inventory so what i could do is say something like inventory at and then item underscore id is equal to and i could say name is equal to item.name i could say brand is equal to oops to item dot brand and then price is equal to item.price now we'll leave it like this for a second but i'll show you kind of a better way to do this but i just want to show you this how you access all of the fields from this item right you just use dot name dot brand and dot price like that and now we would have added this item to the inventory and now what i'm going to do is return a response and what i'm actually going to return is just inventory at item id just to indicate that hey this was all good now your item is in the inventory and we just return the same item back to them so now i think that's all working okay good so let's refresh this uh just sometimes it glitches out and you have to like press enter in your terminal to like refresh the web web app web service whatever it is anyways we're going to have create item now so if i go to create item what i can do is say try it out notice that now we have a required item id since this is required what i'm going to do is pass an id of 2 i'm going to say name and we'll make this name equal to eggs this price will be like 4.99 and then the brand well we actually don't need the brand so let me just remove that and now let's press execute so now when we do this notice that we get our response body saying name eggs brand null price 499. that's now added into the database so now if i go to get item and i try to get item of id two and i press execute you're gonna see oh that we get this issue and sure the value is less than two so obviously we need to fix that we need to make it so we're no longer checking if the uh what is it if we're less than two because we don't really want that constraint okay so if i save this now and then i go back you'll actually see that if i try to run this we're not going to get anything the reason we don't get anything is because this these items are being stored in our memory so as soon as this server refreshes any items that we added are automatically going to disappear hopefully that kind of makes sense but since it's just a python dictionary it's not persistent it resets every time the server restarts and so that item we just added is now gone but i promise you it would work now we would be able to get that item but as i was saying this probably isn't the best way to insert items because well i'm just kind of like copying stuff that we already have what i should do instead is just insert the item object into the dictionary and then if i actually go ahead and return this this will still work the exact same way because fast api is smart enough to take this object and convert it into json since it inherits from base model so we don't need to do anything fancy to convert this to a python dictionary we can just return the item itself and this will still work but what that means is that now if we're going to be inserting kind of item objects into our dictionary we need to change the way that we're looking up items so rather than saying if item or if inventory item id at name we're going to say if inventory item id dot name equals equals name then return inventory at item id and now that should be good and all should be working but we have one problem here we need to change uh this inventory object right here to be an instance of item or we can just remove it and have an empty inventory to start which is actually what i'm going to do hopefully that kind of makes sense i know i'm going like kind of fast through this but there you go that's how you create a new item and that's how you take in a request body so let's just test this out let's go here and just refresh the docs okay now let's go to create item let's make an item so let's try it out let's say item id 1. let's just make this eggs 2.99 again we won't have a brand here execute looks like everything is good we inserted this item so now let's do another item let's do id2 let's make this milk okay let's make our price 4.99 and we can add a brand for this one let's say brand is equal to large and let's go execute and there you go we got that item so now if we go here to get item by name let's look for an item named milk notice that we do get that item let's look for an item named eggs notice that we get that item and now let's go look by id and if we go for id 1 we can see we get eggs if we go for id 2 execute we see we get milk all right so that is awesome that is all working next thing i'll show you is how we do a uh how we actually update an item so if i say app dot and then i'm gonna use put put is to update right i'm gonna say slash we'll call this update item and then what we'll take here just to kind of mix it up is actually a query parameter so the query or sorry not a query parameter we'll take a path parameter so i'm going to say item underscore id and i guess we're not really mixing it up because we just did it here but regardless i'll call this update underscore item and what we'll take here is item underscore id that's an int and then we want a request body as well and so i will say item and i'll make this equal to item so now all i'm going to do here is the exact same thing i did previously i'm going to say if item id and inventory literally have the exact same so if item id in inventory oh sorry not in inventory then i'll say error item id does not exist because notice we're updating an item here not creating a new one so item id does not exist and then if the item did exist what we'll do is just override that item with the new what do you call it the new item that was just passed to us and in fact i'll show you kind of a fancier way to do this i'm going to say inventory item id dot update with item so what this dot update will do is take in the kind of dictionary or json that is this item and it will use it to update the item that we have now what that will mean is that if we don't pass name price brand so on and so forth it will not change the name and the price and all of those other things so if we just passed name then it would only update the name of this item if we just pass price it would only update the price if we passed any combination of these would update any combination of them the only problem however is though since we have this equal to item that means that it's requiring us to take name and take price in so instead what i'm going to do is make a new class and call this update item and all i'm going to do is change these all to be optional so i'm going to say equals none equals none and then we'll make this optional like that so let's go optional like that okay so now this should be good we're going to change this type now to be update item like that okay so hopefully you guys are clear but this should just update the item for us so now we're going to have to go and add a few sample items so let's refresh this here notice that now we have this update item which is a put request so let's just go to our post and let's create an item item id 1 we can just make this milk again price of 299 and then we won't include a brand okay so now if i execute this i think we're all good nice so let's now update this item so to update this item what i'm going to do is try this out item id1 and now i will only include a brand so if i only include a brand now and i make this equal to large and i press execute internal server error what is the error here item object has no attribute update oh okay sorry guys i had a little bit of mistake here i kind of was thinking that this inventory item id is equal to uh a python dictionary which we could use the update method on it's not equal to a python dictionary so instead we're going to have to update doing something a little bit differently what i'm going to do is say inventory at item id dot name is equal to and then this is going to be item.name but we'll say if item.name does not equal none else we won't do anything so actually i think we'll have to change this a bit okay i'm just going to say if item dot name does not equal none then inventory at item id dot name is equal to item dot name and then we'll do the same thing for brand and the same thing for price kind of an annoying way to do the update here but just what we have to do so i'm going to say item.price item dot price item dot price and then same thing here if item dot brand and then brand and then brand okay so again the reason i have to do this is because i thought it was a python dictionary thought i could use that update update command but since it's not a python dictionary it's an instance of this object we have to kind of manually update it and so what i'm going to do now is oops i guess running that's not really going to do anything let's rerun our server here let's go and let's refresh we're going to have to create an object so let's just make one fast one we'll say this is of type milk say price 299 and then we won't include a brand okay let's go execute uh all good what does it say executing property name enclosed in double quotes um okay so the reason that was uh glitching out was i had a comma here and i can't have a comma at the end if i don't have another value after so anyways we just created the item you can see we have name price and brand is equal to no okay so now that we have that uh what i'm going to do is try to update this item still not quite sure if this is going to work but let's go to item id uh what was the id we inserted i think it was just one okay one and now let's just include a brand so we're going to say brand and we'll just make this equal to large and let's execute and now notice that we updated the brand here and we made it large so now if we were to change this and we remove brand and we make this name and we change the name which is supposed to be lowercase to be eggs because right now i think it's milk yeah it is milk and we execute this notice that now we've updated the name of this to be eggs and so that is how you can update an item and now if we go and we look for an item so get item by name we can look for the name eggs and notice that we are getting eggs now of course we could do this the manual way get underscore item or get what is it hyphen item actually what did i call this i want to make sure i don't mess this up get by name okay get by name and then this is question mark and the name that we pass is name equal to eggs it works the manual way as well awesome okay so that is kind of it for the put and for the post now let's do one for delete okay so to do the delete method is pretty straightforward we're going to say at app dot delete we're going to say slash delete hyphen item and then we'll just take an item id actually let's take the item id as a query parameter just to do that we'll say define delete underscore item we're going to say item underscore id this will be an int and we'll make this equal to a query and just add some kind of info here i'll say dot dot and to make sure that this is going to be required not optional and then i will say description is equal to the id of the item to delete and then i will say greater than equals zero so that it must be greater than zero okay now what i can do is check if this item exists so i'll say if item id is in the inventory then we can delete it so we could do this other way actually i'll say if item id not in inventory then what we want to do is return error id does not exist okay otherwise we will simply say dell inventory at and then item underscore id awesome so now this endpoint should be working so now let's go to our docs so let's go slash docs now notice we have this endpoint for delete it's automatically documenting all of it right another great thing about fast api if we go to create item we can make an item so item id one let's just leave it default we'll just we'll just execute one with name string and now let's delete this item so first thing let's just make sure it exists so item id try it out one we get this item okay now if we go to delete and all we do is try it out we pass item id 1 and execute this response body no oh because we didn't return anything from here that's fine but it should have deleted the item because now if i go and look for this item so i go here to get item by id and press execute we get an internal server error because well we don't have that item now let me just return something here let me just return you know success item deleted or something okay item deleted exclamation point great okay so that's good we now have the update create delete and then get by name and get by id all right so now we're nearing the end of this tutorial and i'm going to show you how you can actually return different status codes from these uh these endpoints because you can see here that for example i'm returning like some data that says error id does not exist but the status code when i return this is still going to be whatever the default status code of delete is and that's no good now if you're unfamiliar with status codes every single time you call an http endpoint it will return to you some status code that indicates kind of what happened the default is 200 that stands for ok 201 is created 404 as you've probably seen before is not found there's a bunch of status codes you don't have to memorize them obviously but i'll show you how you can return like an error status code rather than just returning some data that has the same status code as whatever the default you know return status code of delete is and the way you do that is you go up to fast api you import http in all capitals exception like that and then you import something called status all right so import both of those now i'm going to go to a place where we have some error message so here it's saying data not found and rather than returning data not found when you want to actually give some type of error message with a different status code you just raise a python exception so if you raise exception and this exception should be http exception what you can do is indicate the status code so you say status code like that make it equal to whatever code you want in this case i can say something like 404 or i can use the status dot then http underscore 400 or underscore 404 underscore not underscore found i think that's what it's called so this kind of status module here has like the actual names of all these status codes in them if you'd prefer to type it out this way when you do status dot http underscore 404 not found this whole thing is just equal to 404 it just makes it easier to kind of read it out anyways i just want to show you that i'm not going to use status but you guys can use status if you want what's known as like the enum for each value and then you can say let me check here in my cheat sheet i believe it's detail and you can give the detail of why this this error was returned so i can say detail and say item id not found or something like that or item name not found okay so let's just copy this and let's paste this in all the other places we have an error so rather than raising this error we'll say item id already and then exists and i don't know what status code we should use for this one i'm just going to use 400 i think 400 stands for bad request i'm not too fussed about doing this all properly i just i'm trying to show you how we can raise these errors and then let's raise another one here so rather than item does not exist we'll just do 404 we'll say item id does not exist and then do we have any more errors this one as well so we can just copy this exact same thing so raise http error let's copy it here and there we go we are now good and just to give you an idea of what's going on when we do this in the back end so in fast api it's kind of waiting for one of these exceptions to be raised when it's raised it will automatically return the equivalent kind of http response so that we don't have to do it manually instead we can just raise an exception so let's now go here and let's refresh our docs i'm going to have to press enter in here okay reloading that's all good now what i'm going to do is go to get item let's try to get an item id1 when we do this oh i forgot we haven't fixed get item by id okay let's let's not do that one let's get item by name let's look for an item let's look for eggs when we do this notice we get detail item not found and our response code was 404 as opposed to 200 which we would have gotten previously all right so hopefully that kind of makes sense let's go and try to create an item so let's go try item one let's just execute that okay let's try to do it again when i try to do it again you're gonna see here that we get detail item id already exists and we get status code 400 telling us hey this was a bad request you can't do that right now if i go to update item and i try to update item id 2 let's go like that again same thing item id does not exist we're getting the correct response all right so i think with that that's actually going to wrap up this video hopefully this gave you and i'm just going to zoom out so you guys can look at all this code here on kind of one screen hopefully this gave you a decent idea of how to get started with fast api i know i went into like a lot of probably unnecessary detail for a lot of this stuff we just want to make sure you guys understand the difference between the path query and kind of request body arguments or parameters that's very very important and once you understand that like you saw here we created pretty well fully functioning api in not very many lines of code now obviously you would want to change this inventory to be an actual database but if you're just working on something simple and want to get it up and running fast fast api is a great choice and yeah i mean i hope this helps you understand the framework if it did make sure to leave a like subscribe to the channel i will see you in another youtube video
Info
Channel: Tech With Tim
Views: 77,291
Rating: undefined out of 5
Keywords: tech with tim, tech with tim tutorial, fast api, fast api tutorial, python api, python fast api, python fast api tutorial, what is api, api tutorial, fastapi, fastapi tutorial, fastapi python, api python tutorial, api python, fastapi python tutorial, json, data validation, auto documentation, auto completion, code suggestions, endpoints, query parameters, post method, put method, delete method, installing fastapi, python json, what is json, json explained
Id: -ykeT6kk4bk
Channel Id: undefined
Length: 58min 20sec (3500 seconds)
Published: Sat May 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.