YTread Logo
YTread Logo

Python FAST API Tutorial

Jun 07, 2021
Hello everyone and welcome to another YouTube video, so in today's video I'm going to show you the Python web framework known as Quick API. Now, as the name suggests, what this web framework allows you to do is create APIs in Python, the reason why it is called Quick API. it's because you can create 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

fast

and very high performance. That being said, this video is not designed for absolute beginners. You should have some knowledge with Python, however I will explain what an API is.
python fast api tutorial
I'll talk about the common API method type, so publish, put patch updates, all those types and I'll discuss JSON and sort of how. an API works if you're not familiar with APIs, don't worry, but you need to have some knowledge of Python to be able to follow along, so with that being said, let's dive in after a quick word from our sponsor before we get started. I must thank Intel. for sponsoring this video and having me talk to you about your openvino toolkit and the Intel Dev Cloud for the Edge. The openvino toolkit is free software that helps developers and data scientists accelerate computer vision and AI workloads, streamline inference and deep learning deployments, and enable heterogeneous processes. running on the entire Intel platform from edge to cloud on the openvino website you can find free resources such as 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 openvino toolkit you can use intel dev cloud for edge.
python fast api tutorial

More Interesting Facts About,

python fast api tutorial...

This is a cloud-based development sandbox that gives developers access to the latest Intel hardware and software to build, test and prototype their AI. Applications With these technologies and resources you can create, 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. When we get into the video here, the first thing I'll mention is that there are timestamps linked below if you want to skip to a certain part of the video or if you want to skip the beginner explanations, maybe if you're more advanced.
python fast api tutorial
Regardless, I'm going to start here by discussing the main advantages of the Fast API and why you might want to use it so fast. The API is very fast to create a correct API. The name is very appropriate and one of the reasons for is to say, when you create an API in a quick API, you will actually define the types of all the data that your API expects so traditionally when you write an API or some web framework or something as well as a web application in Python. You don't actually explicitly state what type of information your endpoints are going to accept, sort of like a URL on the server.
python fast api tutorial
What that means is that you have to do a lot of data validation that you have to check to make sure that you know that you actually got an integer, you got a stringer, you got some json object or something like that and while this is a lot of work hard and you're just writing a bunch of stuff to essentially verify that the information that was sent to your API is correct now in quick API all of this is actually done automatically for you so if someone sends the wrong piece or the type incorrect information to your API endpoint, it will automatically return some kind of error message that says, "Hey, you already know this." It was supposed to be an integer and I got a string, but that's the first main advantage of the Quick API is that it does all this data validation for you because when you create endpoints with Quick API, it will explicitly define what type all the information that will pass past that endpoint will be like this, whether it's a route parameter, a query parameter, or actually the type of request body that you're going to define exactly what it should look like so that the API can automatically handle the data. validation The next thing that's great about the Quick API is that it automatically documents the entire API, so since you're actually providing all types of what's expected for the API, the Quick API can automatically generate documentation that also works kind of 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 and see. all the API endpoints and exactly what they expect and any description or information that you would have provided them and then the last thing, since you're defining the types of all this kind of information related to the endpoints, you'll get really good autocompletion , so if you're working on a real idea like vs code or pycharm, I'm not doing that right here, I'm on sublime text, so you get really good autocompletion and better completions than you normally would due to the fact that you're defining these guys, so anyway, let's talk enough.
In it, the first thing we need to do is install Fast API, so if you are on Windows, open the command prompt. If you are on Mac or Linux, open the terminal and you will 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 requirement satisfied try pip 3 install fast api if that doesn't work for you try

python

hyphen m pip install fast api yes that doesn't work for you try

python

3 script m pip install if none of them work for you go to the links in the description.
I will have a video for Mac and a video for Windows that will show you how to fix this problem. command now, once we've installed the quick API, I'll assume you've done it. At this point, we will install something called uv corn. Now this is what we will actually use to run our API. like a web server you'll see in a minute, but anyway you also need uv core again, if this command doesn't work, try those pip 3 python m sequences, so on, so we can exit the command prompt. open, we'll use it later, so what we have to do is open a Python file in some editor for me.
I am working on some directory. This on my desktop is called Quick API. You can see it in the upper left. In the corner of my screen to see the path of 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'll need to access it. Okay, now what we're going to do is make sure that our quick API installation is working, so we're just going to import a quick API, save our script, run it. I'm running mine with Ctrl B on sublime text and you can.
Look, we don't have any mistakes, so we're all good. The API was quickly installed, so now let's write our first API. I'll go through this pretty quickly, just show you how to set it up and then We'll go through each line and discuss what I did, so I'll say from quick API import and then I'll make sure to look at the caps here quick API. This is the first thing we should do, we are going to import. this quick API class module, whatever, and then we'll say application equals and then a quick API with an opening parenthesis and a closing parenthesis, what this will do is create something like, let's say, an object of API, something that's going to Initialize our API and say, "Okay," this application variable right here tells us that we just created our first quick API, regardless of whether that's what you should always do when you start working with an API fast.
Okay, now that we have this, we can create an endpoint and right now I'm going to stop for a second to quickly discuss what an endpoint is, so if you hear me say endpoint or root or path or whatever that is really mean is something like slash, slash, you know, get script element, so when you talk about an endpoint you have kind of a base server URL, in our case our base URL is going to be localhost because we're not distributing this application , I guess we are deploying this application. We're just hosting it on our local machine so the base URL would be localhost and then the endpoint would be slash hi so you have all these different endpoints and when you go to these different endpoints different things happen but there will be different information. returned to you, maybe you're sending information to an endpoint, but regardless that's what I mean by endpoint slash, something essentially correct, it's like the end path after the parent domain, so if you were looking , it will know like facebook.com, full stop.
It would be like a slash to the right, that would be one of the endpoints for facebook.com, regardless of whether it is an endpoint, so to create an endpoint what you do is say app dot and then the method that this dot end is going to accept or that's It's going to be like that when we talk about the http hypertext transfer protocol, I think that's what it means, at least we have a few different main methods, so whenever you configure an endpoint, you can configure it so that be a different method if that does it.
I feel like I'm having trouble finding the exact word, but the idea is that we have these kind of core http methods and they all mean something different now, one of the main ones is get, we have the post that we put in and then we have delete and we also have a few others, but these are the main four now, when you set up a get request or have an endpoint that has a get method, what this means is that this endpoint will return information. That's all it does: ask this endpoint to get something for you and give it back to you.
That is the get http method. Now when we talk about publishing, this actually means that you will send information by publishing the endpoint or this endpoint here i.e. the method, publishing will create something new every time you are creating data, like adding something to the database. data. You're doing this with a publish request, so maybe you'd publish a new user login or something. right or a new user registers successfully, I would post it to an endpoint because you are going to create a new user in the database because you just registered or registered or whatever and then put this is to update something that already exists in the database, you know, modify the information essentially and then delete it, that's simple, you're deleting something, getting rid of the information now, of course, there are a few more, but these are the main ones, the ones I'll show you, depending on method that you want to be your endpoint, it's going to say app dot and then method, so in this case I'm going to use get and then it's going to put the endpoint right here, so I'm going to say forward slash and make sure you apologize before the application put this in the symbol here.
I'll discuss why we need it in a second, so for now I'll set up what I'll call my starting endpoint and what this is. What I'm going to do is just return some data that says test, so what I just did is what I said in app.get. I have defined my root or endpoint type as forward slash and then created a function. called this home, make sure your root type or endpoint is right above the function that's going to fire when you go to this root and then what it's going to do is return some Python dictionary, this is going to be the data type or the information that will be returned when you go to this endpoint, so hopefully that will make sense, but if we go to cut now, once we run this web server, what will happen is that the information data with the test key will be returned, so this This is how you set up a root, you say at the application point, whatever the method is, again, the root, you define a function right below it, you can name this function whatever you want and then you return information, okay, There we go, so let me.
I'm going to show you how we can run this, then I'm going to talk about what's known as json and what an API is and actually how it works, so what I'm going to do here is I'm going to go to my command prompt and I need to change directories. in the folder or directory where my python script is. In this case, I'm on Windows. I'm starting in my home folder, so I'll go to the CD desktop and then enter the CD in the quick API. so what I'm going to say is uv cable, this is what we just installed and I'm going to say the name of my file that is working.
Notice, I'm not going to add the pi dot, you don't want the pi dot. so make sure you don't have that and then wow, what did I just do here? Well, anyway I've messed up my cursor somehow. uv corn working two points, then you will say application, the application being thename of the variable you have quick. api stored in and then space script script reload now what this script reload script will do is tell uvcorn to constantly reload the web server every time you make a change to the python file that stores the API, so uvcorn the name from your python mine file is working, notice I don't have the extension dot pi, then the name of the variable that stores the quick API, colon, colon or sorry, dash, dash reload and then press enter and it should see it says application start complete and shows you the url.
Right here you need to go to access this website or access this API. Sorry, in this case it's http colon 127.0.0.1 colon 8000, pretty much the same as localhost, so what I'm going to do now is go to my browser. and say http forward slash 127.0.0 colon8000 and I'm not going to go to the docs page yet and here you can see we get this data that says test because we went to the forward slash end point so when you just put forward slash that means if you go to any endpoint essentially on the server, like you just go to the default to have nothing after it, then it will return or treat it as if you were at this endpoint, so I think you guys understand what I'm saying I'm mumbling for here, but the point is that this is equivalent to the trailing slash at the end, regardless, you can see we're getting data tests, so now let's make a quick change.
I'll say I'm trying. I'm going to save that now. I'm going to go over here and refresh and notice that it says "testing," which means our reload is working great. Now, what you saw, I accidentally loaded this document page, so we better go to it. Right now, if you go to your server URL, which is just 127,001 thousand colonies, then slash docs, you will have automatically generated documentation for your API, so at this point we only have one endpoint, it's the slash, the function name is at home that's why it's saying start and then if you press this it says ok it doesn't take any parameters and what if we test it we can test it by pressing that button and press run we can see the body sample response. we can see the request we sent to get this response.
This is a way you can test your API from this docs page right here. Alright, I'm going to quickly break down what an API is, so API stands for application programming interface. and really what an API is is a web service that provides an interface to applications to manipulate and retrieve information, so if we're talking about something like Amazon, I almost definitely don't know the internal makeup of Amazon, but it almost definitely has a API. now they probably have multiple APIs, but one of their APIs may be responsible for properly handling your type of inventory system, finding out what items are in stock, what items are not in stock, how many items are in stock, how much they cost, all that stuff. it occurs to us. a common API that Amazon may have as an inventory API.
Now this API here is separate from the different interfaces that display this information, so if you're talking about Amazon, they have a web app, they have a mobile app, they have something that works. like alexa or google home or whatever, they have all these different services that depend on the same underlying information, they need to know the inventory, they need to know what's in stock and so instead of typing, you know five delivery systems. inventory management, they would write one. in the form of an API application programming interface and now any of your applications that your users use can access this same information by sending requests to the API, so that when you go to the website you know and search, I don't know.
Let's say graphics card, none of them are available at the moment. What will happen is it will send a request to the Amazon API that says "Hey, I'm looking for graphics cards," and then it will return all this information to the interface and it displays all of that for you and then when you click on a graphics card specific, it will say oh I need all the information related to this graphics card again, a request will be sent to the API, the API will then send all that information to the front and hopefully that will give you an idea of ​​how the communication works, but The same thing that happens in the mobile app, you send one request to the API and this way you don't need like five. different backends to handle each of your applications and all its information, you have an API responsible for distributing and giving you all the information you need and this is a good practice when you write code, it is a very good idea to separate the front-end and the back-end, so if you ever want to create a different type of representation of your data on the front-end, you can use the same API and the only thing you need to change. is the way it is displayed so I hope it gives you an idea of ​​what an API is and how it works.
Now I don't know the internal makeup of Amazon Web Services and all that kind of stuff, so I could be completely wrong with what I described, but that's as an example of where it might make sense to use an API. That being said, what I need to talk about quickly is the data that APIs exchange or I guess anything over http actually gets exchanged. Here we returned a Python dictionary. Now this Python dictionary is automatically converted to something known as json javascript object notation as soon as it is returned from this function, so the quick API actually handles jsonifying all of our information so we can work with strictly Python types.
In our current API, this may seem a little confusing, but whenever you return information from an endpoint, it is standard for that information to be in the json format. Now you don't really need to know what json is or what it looks like. it's just a little bit different syntax than the standard Python dictionary and, well, here you can understand that in a fast API, any data you return from your endpoints is automatically converted to json, so whoever receives it on the other endpoint you may have data that looks a little different than what you returned just because everything will be converted from sort of basic Python types to this json format.
Now the same thing when these endpoints receive information every time they get a query parameter. The request body will come as json and will be converted to basic python types, so we don't need to worry about dj type sonify or jsonify all our data, just make sure you understand that all data exchange type between apis is in the json format, we're lucky that the quick API can convert all of this into basic python types for us anyway, it was a lot of conversation, I hope I don't bore you too much with it, but if you guys are beginners, I hope that helped you Helped, let me know in the comments.
Now let's continue working here and create some more endpoints, so I'm going to create a new endpoint here. I'm going to say app.get and let's do this. slash now what's this going to do, I'm going to say define about and, wow, if I can write about correctly and here I'm just going to return some data and I'm going to return the data and about just so we have another endpoint so we can see how this works when we look at the automatic documentation, so now my web server should have been updated. If I go to the docs, I notice that I have another endpoint named correctly and if I press this, I can press test it.
I can hit run and when I run that notice that we get our data, we now get the same thing here. If I go to cut, we can see that we have data on Awesome, so those are two examples of using an endpoint that has the get method now we can also 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 route parameters and query parameters, and to do that we're going to go into our first example here, so I want to treat this API that we're creating as sort of an inventory management system like the example I gave you from Amazon, so I'm going to say inventory, I think I said that correctly. equals to and we're going to make this a dictionary now inside here we're going to store a bunch of different stocks, all the different items that we can have in stock and all of these items will have a unique ID so the key in this dictionary will be its ID, like this which I'm going to say you know the item with id1, the name of this item is let's say milk, maybe let's treat this like a grocery store or something, the price of this item. it's, I don't know how much milk is, let's say 3.99 and we'll say maybe the expiration, uh, this could be actually, I don't want to do something like a date right now, let's do something else, milk, maybe just say . brand and I don't actually even know like a brand of milk we'll just say uh regular now of course there could be a lot more information we're just doing this just for now because we don't need to go into details. anything like advanced crazy, okay, regardless of whether we have the name, we have the price, we have the 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 information from the item to us based on your ID, so what?
What I'm going to do is say in app.get that this is going to be a get method for this endpoint. I'm going to say get element with dash and then what I want is for the user to pass me some ID for this element and then what I'm going to do is put inside the braces the underscore identifier of the element. Now what this means when I do this is that whatever is here could be anything, this element identifier could be literally anything and depending on what this element identifier is. I'm going to return something different from this endpoint, so now I'm going to say define get element underscore and now what I need to do is define a variable to represent this element id, so I'm going to say get underscore id under the element you must match the name here colon int now what this is is a type hint in python whenever you do a colon next to a parameter and then define the type it is known as type hint and the reason Why we do this in the Quick API is to tell the Quick API that this element id is supposed to be an integer, so if you try to pass something other than an integer to this endpoint for the id element, it will be returned automatically, we don't have to do this quickly, the API will automatically return an error. message that says "hey, this wasn't an integer, it has to be an integer and I'll show you how it works, but this is our first example of what's known as a route parameter, so now what I'm going to do is just return and I'm going to return my inventory on the item underscore id, so let's go ahead and take a look at this and see how it works I'm going to go now to the trailing slash and this was get the item with. dash and then forward slash one now when I do that notice it gives me all the information related to that item so I have the name which is milk price 399 regular brand awesome but now if I try to go to something that is 2, we get an internal server error.
The reason we understand that is that there is no element with id2, so this line here causes an error. I'll show you how we fix it later, but I just want to show you. that and finally, if I try to do something like go milking. Notice that we get this detailed error message saying, "Hey, this value is not a valid integer." You have to give us a valid integer and it even tells us that the element id is wrong and that's how you set up some sort of route. parameter can now also set multiple route parameters, maybe we have items that have the same id or maybe we just want more information from this user.
This example will make a lot of sense, but I'll just show you how it works. we can take an element id and we can take something like, I don't know, maybe a name now that we have this name here, we would need to go inside our parameters, uh, what are they called? uh, here and define the name, colon string, which says Okay, this name here is expected to be a string and then what we could do is just return the inventory item id and maybe we could add something to this . I'm trying to think how I would do this.
I can say period. I update and actually no, this is not going to work at all. There's not really a way to return the name string that will make sense, so anyway I just want to show you that we can take multiple route parameters, so now if I go here. and I update this, so let's get the slash test from element 1. Notice this still works, it's totally fine, we take another path parameter and well, everything is fine, so I hope that makes sense, but like this is how they are takenmultiple path parameters within Your endpoint type is fine, sorry for the abrupt break.
Anyway, I had some problem with my editing software. What I'm going to show you now is how we can add more details to our route parameters, so I'm going to remove the name. Since we don't want this anymore, I'm going to remove it from the actual parameters and now what I'm going to show you is something known as route, so we're going to import this function called route and what we can do is set our element ID colon int equal to and then this type of route function right now, what this is going to do is allow us to add more details or some kind of additional application or constraints on our actual route parameter, so for example, if I wanted to add a description to this route parameter to tell the user what it's really like, the information they need to pass for the element id, I could say something like description equals and then I can write a description and for my description.
I'll just say the ID of the item you'd like to see and then one thing here before I do the description. I always need to give a default value for this so I'll say none and then describe the id of the element you would like to see now, I understand this may seem a bit strange but as long as you use these types of functions within the parameters for a endpoint, you should always start with the default value for this parameter, so if the element id was You didn't pass what should be the default value, in this case the default value will be none, so if you don't pass an id of element by default will be none;
However, you'll see that we're talking about route parameters here, it's actually necessary for you to pass an element id so that we never end up using the default value. I know this can be a little confusing. This will make more sense once we move on to the next thing, which is the query parameters, which can be optional regardless of me. I'm going to put none here. I'm going to say that the description is the same as the ID of the item you want to see now. If I come back here and we update this to get item one, you can see that everything is fine.
If I now go to mydocuments you can see it says get the item id and notice that now there is a description that says the id of the item that you would like to see because we added that description inside this type of route right here, now we can also What I have to do is have some restrictions on the element id to make sure that it's greater than one or greater than some value, so what I'm going to do is say gt this means greater than and then I'm going to say this is equal to and make it equal to zero, so what this says is fine, this element id must be greater than zero.
Now you can use another few here which means less than that means it must be less than zero, you can make it less than. that or equal to and then you can do ge which is greater than or equal to and you can do any kind of combination of them so you could do maybe uh let's say g t zero and lt is equal to two so now the only valid thing you can pass it's an id of one if you pass anything else you're going to get an error so let's try this first let's update this here and I don't think it's actually going to tell me more than the application here but if I'm going to cut get dash element slash two notice that we have a problem it says message and sure this value is less than two correct because this did not meet the constraint less than now if I do one everything is fine and if I try to do zero we get an error here that says no, this is not valid , make sure this number is greater than zero, hopefully, that makes sense, but that's kind of basic to using this route here, okay, now that we've talked about route parameters, the next thing we need to talk about are parameters query parameter, 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 to facebook.com and then a leading slash and then there is something like a question mark. and it says like you know key equals what it says like redirect equals and then maybe some page and the thing is this is what's known as a query parameter so as long as you have a question mark and then have some variable name equals and then some value this is a query parameter and it can have several of them, let's just do the redirect like slash tim and then we would do a sign and then we would say you know msg is equal to fit and now we have two redirect query parameters which is equal to sim and msg which is equivalent to fail, so how do we accept the query parameters for our endpoint?
I'm going to create a new endpoint here and show you how we do this. I'm going to say app.get and make this get. by name get by name colon and what this will accept is a query parameter and this query parameter will be the name of the element that we want to retrieve so what I'm going to do here is say name colon str now what this says okay, we're going to accept a query parameter called name, so by default, if you don't see this variable that you've defined as a parameter in the path to the endpoint, it's going to be a query by default. parameter, this means that we are looking to accept a parameter called name that is equal to a string, so I'm going to show you how it works, but that's pretty much what it means and now what we would need to do inside of here is we need to look at our inventory and find something that has the name of the name that was passed in, so what I'm going to do is do a for loop here.
I'm going to say 4 items in the inventory and actually this should be 4. id in the inventory actually I can't call it id, I will call it item underscore id, I will say for the id of the item in the inventory, if the inventory in the item's underscore id in name is equal to name, so what we'll do is return inventory in item's underscore id, otherwise if we get to the end of this and that doesn't work, we'll return something that says data no found. Now that we've created an endpoint, it's taking a query parameter called name, so let me show you. what we would actually call this endpoint, so if I go here now and change this to get what we call it get by name, get by name with hyphen and then do a question mark and say name equals 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.
We don't pass any query parameters and we just do this, it tells 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 also add multiple query parameters. We could add like price, we could add brand, whatever, if we wanted to do that and anyway now let me show you how we can add more details to our query parameters and how we can make them potentially optional, so now we put the name here is 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 it can call this endpoint without this query parameter, in that case we would just set this equals none and now What this means is that since it has a default value, this query parameter is no longer needed, it automatically becomes optional, so if I save this now, I go back and just run this notice that this works we will no longer get an error because now this query parameter name is strictly optional we can pass it but it is not necessary and by the way it is recommended in the quick API docs that you do the following when you have an optional parameter , say from and type import and then you're going to import optional and then you make this type of string optional.
Now you don't have to do this. You saw this worked when we didn't do this, but this will just provide better autocompletion for your editor when you decide to do this, so it's optional, it's strictly for you as the developer, it just makes it easier to improve autocompletion when write code here, make an optional string to note that yes, this parameter here, the name is actually optional, so if I run this you'll see when I save this, this still works, it's totally fine, so I hope that's clear , this is how you make a query parameter just to quickly show you that we could make another query parameter, you could say, let's do this test, maybe this is an int and maybe we want this to be required, you have to pass the test, so now that I've done this, this means that if I update this now, let me go over here and just hit Enter, oh, what's this name? -default argument drops ah ok actually that's a good bug let me discuss this so we get an error here saying that a non-default argument came after a default argument so for a fast API no It matters the order in which you write these different parameters so that it doesn't matter if you know the element id first or if you have the name first.
If you test first, the fast API will be able to solve it, no matter what order you put. However, in Python, it actually gets a bit annoying when you put something that is not required or put something that is required after something that is not required, so the way around this is that you can reorder this placement test first when I say it means we could do a test like this or what we can do is just add an asterisk like this and then put a comma now if we do this everything will essentially work. This is a little hard to explain exactly what it does, but this says, "Okay." let this function accept unlimited keyword arguments or unlimited positional arguments and then the rest of them should be treated as keyword arguments.
I'm not really going to explain why it works, but if you get some error saying, "Hey, you know all your parameters are sorted." incorrect, just put an asterisk first and this will fix it, so if I go here and update this, now you can see it says field required, we're looking, oops, get by name, message field required, type query test, okay , I'm sorry. I'm just trying to figure that out, so now everything is working, but if I now say test equals 2, you can see we're all good because we pass the required keyword argument and I can pass another keyword argument, let's say that name equals milk if I do this correctly, I press enter and what is the value of the message?
Oh, sorry, this should be an ampersand, not a question mark, so let me try to fix this sign, okay and now we're good, now we get the article, milk, hopefully. that's clear that covers the uh what do you call keyword arguments or sorry no keyword arguments query yeah query parameters that's what it's called now let me show you how we can combine query parameters and route parameters together , so let's say get element by name we wanted to accept a path parameter as well as some query parameters, maybe we wanted the element id and we wanted the name.
I don't know why you would want that, but maybe you do, in this case we can say element underscore. id and now what we need to do is make sure we have a variable called element id which is inside 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 element id colon int and now this will work . Now we can accept our element ID as a route parameter. Our name as an optional keyword. I'm sorry. Optional query parameter and then try as required query parameter.
Now if I do this, I go here and Refresh, we don't meet, but if I make a slash and then a question mark, I notice that this works fine, we're all fine and yes, it's fine, so I hope that illustrates to you how works, but this is how you can combine route arguments. and the query arguments are fine, so now that we've looked at the query and path parameters, we're going to go ahead and talk about the request body a lot of times, especially when you're trying to add information to a database that you're not going to.
To send all of this information in query parameters or route parameters, you're going to send a bunch of information as what's known as a request body, so I'm going to set up an endpoint here, I'll say in app.post, so this time it's a new method. I'm going to say forward slash to create element. Now what we're going to do is change this a little bit so that we now 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 accepthere is a request body.
I want information related to the item, so I want the name of the item, the price of the item and potentially. I also like the item flag, 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 called item, so whenever you're looking for a request body, like this that I want something that is not a query parameter and I want something that is not a route parameter. I need to set it equal to a class that inherits from something known as a base model.
Now I'll discuss this in more depth in a second, but let's go 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 element that inherits from the base model and now I can. define in this class the type of data structure that I'm looking to accept as this element parameter right here to create an element, 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 flag and this will be optional because I don't know if I'm going to take a flag every time the string is equal to none, just like it worked for query parameters and route parameters, if you want them to be optional you can add this kind of optional element which is not necessary but it's good practice and then set it equal to none or set it equal to some default value and that now makes the flag optional. Awesome, now that we have it, I'm going to save this and what this can do. Let me go here and return some kind of empty dictionary for now so we can see how it works, but since this is equal to this class, this is now telling the quick API that okay, this is for the body of the request , this is not a query parameter, so it doesn't expect me to do something like the question mark element is equal and then write it all out, you know I'm going to send the information for this element in the body of the request, okay, so I'll go over here and update this and let's see if anything went wrong.
It looks like everything is fine, so now if we are looking at our documentation we see that we have this new endpoint called create element, so look, it says the request body is required, we look for a name, a price and a brand , and if we wanted to try this, we could, although right now it's not possible. work, it's not going to do anything, although if I press try and I can just submit this and I press run, I notice that we're getting an empty response because we haven't written anything, so what I want to do now, though, is take this item and I really want to insert it into the inventory.
What I can do is, instead of trying to create a structure that looks like this, I can just insert this actual item, which you'll see in a second, so what I'm going to do here now is change the item creation to which also accepts an id, so I want an underscore id of the element. The reason I want an element id is because if I am going to insert this element. well I need an id associated with it so now I also need an element id here so I'm going to say element id colon int now it's going to be assumed to be a path parameter because it's on the right path so we have our element for the request body and we have our item id which is an awesome route parameter, so now the first thing I'm going to do is check if this item id already exists.
I'm going to say if the item id is in and then this would be an inventory, let's go here, so what I want to do is just go back and we'll say the error item already exists or the item id already exists. Great, if that's not the case, we can just add this item to the inventory, so what you could do is say something like inventory in and then underline the item. id equals and you could say name equals item.name, you could say brand equals ups to item dot brand and then price equals item.price now we'll leave it like that for a second, but I'll show you a better way to do this, but I just want to show you how to access all the fields in this article.
Simply use the point name, point brand and point price like this and now we would have added this item. to inventory and now what I'm going to do is return a response and what I'm actually going to return is just the inventory on the item id just to indicate that, hey, everything was good, now your item is in inventory and just return the same element to them, so now I think everything is working fine, so let's update this, it just sometimes crashes and you have to press Enter in your terminal to update the web app's web service, whatever it is anyway .
I'm going to create an element now, so if I'm going to create an element, what I can do is test it. Note that now we have a required item id, since this is required, what I'm going to do is pass in an id of 2. I'm going to say name and we're going to make this name equal to eggs, this price will be like 4 .99 and then the brand, well, we don't actually need the brand, so let me delete it and now let's press run, so now when we do this notice that we get our response body that says name eggs brand price null 499. that now it's added to the database so if I go to get the item and I try to get the item id two and I press run you'll see Oh we have this problem and we're sure the value is less than two so obviously we have to fix it.
We need to do it so that we're no longer checking if, what if we're less than two why not? I don't really want that restriction, so if I save this every once in a while go back, you'll see that if I try to run this we won't get anything, the reason we don't get anything is because these items are stored in our memory, so as soon as this server updates any item we add will automatically disappear, hopefully that makes sense but since it's just a python dictionary it's not persistent, it resets every time the server restarts and that item we just added already it's not there, but I promise you it would work now that we could get that element, but like I was saying, this is probably not the best way to insert elements because, well, I'm just copying things that we already have what I should do instead, just insert the element object in the dictionary and then if I actually go ahead and return this, this will still work exactly the same because the quick API is smart enough to take this object and convert it to json. since it inherits from the base model, so we don't need to do anything fancy to turn it into a Python dictionary, we can just return the element itself and this will still work, but what that means is that now if we're going to insert type objects of item in our dictionary, we need to change the way we look up items, so instead of saying if item or if inventory item id in the name, let's say if the item id point name inventory equals name and then return inventory on item id and now that should be fine and everything should be working but we have a problem here we need to change this inventory object here to be an item instance or we can just delete it and have an empty inventory to start.
Which is actually what I'm going to do, I hope it makes sense. I know I'm moving a little fast on this, but there you have it, this is how you create a new element and this is how you take the body of a request, so let's go. just try this, let's go here and update the docs, okay, now let's create an element, let's make an element, so let's try it, let's say element ID 1. Let's make these eggs 2.99 again, we won't have a tick here, run looks like everything is fine, we insert this item, so now let's make another item, let's make id2, let's make this milk, okay, let's make our price 4.99 and we can add a mark for this one, let's say mark is equal to big and we're going to run and there. see, we have that item, so now if we go here to get the item by name, let's look for an item called milk, notice that we get that item, let's look for an item called eggs, let's notice that we get that item and now let's go search. id and if we choose id 1 we can see that we get eggs, if we choose id 2 we run, we see that we get milk, so it's amazing, everything is working.
The next thing I'm going to show you is how we do a uh how. we actually update an element so if I say app dot and then I'm going to use put put is to update, right, I'm going to say slash, we're going to call this update element and then what we're going to take here just to mix it up is actually a query parameter , so the query or sorry it's not a query parameter, we'll take a path parameter, so I'll say element underscore ID and I guess we're not mixing it up because we just did it here. but regardless I'm going to call this element update underscore and what we're going to take here is the underscore ID of the element which is an int and then we also want a request body so I'm going to say element and make this equal to element like this that now Everything I'm going to do here is exactly the same thing I did before.
I'm going to say if the item id and inventory have literally the exact same thing, so if the item id is in inventory, sorry, not inventory, then I'll say error item. The id does not exist because notice that we are updating an element here, not creating a new one, so the element id does not exist and then if the element existed, what we will do is we will simply override that element with the new one, how do we calls? new element that was just passed to us and I'm actually going to show you a more elegant way to do this.
I'm going to say inventory item id dot update with item, so what this dot update will do is it will take the dictionary or json type that this item is and it will use it to update the item that we have now, which what that will mean is that if we don't pass the name, price, brand, etc., it won't change the name or the price, and all those other things, so if we just pass the name, it would just update the name of this item, if we just we pass the price, it would only update the price if we pass any combination of these, it would update any combination of them, however the only problem is However, since we have this equal to element, that means it requires us to take the name and the price , so what I'm going to do is create a new class and call this update element and all I'm going to do is change. all of these are going to be optional, so I'm going to say equals none and then we're going to make this optional like this, so we're going to be optional like this, okay, now this should be good, let's change this type now to be update an element like that, okay, I hope you guys are clear on that, but this should just update the element for us, so now we're going to have to go and add some sample elements, so let's update this here.
Note that now we have this update item which is a sell request, so let's go to our post and create an item with item ID 1, we can make this milk back to a price of 299 and then we won't include a mark, okay, so now if I run this, I think we'll be All good, so now let's update this item, so to update this item, what I'm going to do is try this item id1 and now I'm just going to include one mark, so if I just include one mark now and make it equal to big. and I press run internal server error what is the error here the item object has no attribute update oh ok sorry guys I had a little error here.
I was thinking that this inventory item id is equal to a Python dictionary that we could use the update method because it's not equal to a Python dictionary, so we'll have to update by doing something a little different. What I'm going to do is say that the inventory in item id point name is equal to and then this is is going to be item.name but we're going to say that if item.name is not equal to anyone else, we're not going to do anything, like this I actually think we'll have to change this a little bit.
Okay, I'm just going to say if item dot. name is not equal to none then inventory in item id point name is equal to item point name and then we will do the same for brand and the same for price, a bit annoying way to do the update here, but just what we have to do it, I'm going to say item.price item point price item point price and then the same thing here if item point mark and then mark and then mark okay, so again the reasonWhy I have to do this is because I thought it was a Python dictionary thought I could use that update command, but since it's not a Python dictionary, it's an instance of this object, we have to update it manually, so I do it.
What I'm going to do now is wow! I guess running that doesn't really work. to do anything, let's run our server back here, let's go and refresh, we're going to have to create an object, so let's make a quick one, we'll say it's type milk, let's say price 299 and then we won't include a brand, okay, let's run, uh, all right, what does running the property name in double quotes say? um, okay, so the reason it was failing was because I had a comma here and I can't have a comma at the end if I don't have one.
I have no other value after, so anyway we just created the item. You can see we have name price and brand equals no, so now that we have that, what I'm going to do is try to update this article, but I'm not sure yet. yes this is going to work but let's go to the item id, what was the id we inserted? I think it was just one, okay and now let's include a brand, so we'll say brand and do this the same. to large and let's run and now notice that we updated the tick here and made it large, so now if we change this and remove the tick and create this name and change the name that's supposed to be lowercase to be eggs. because right now I think it's milk yeah it's milk and we run this notice that now we've updated the name of this to be eggs and this is how you can update an item and now if we go and find an item so get the element by name we can search for the eggs name and notice we are getting eggs now of course we can do this manually get the underscore element or get what is the dashed element actually what did I call it ?
I want to make sure. Don't screw this up get by name okay get by name and then this is a question mark and the name we passed is name equals eggs it also works manually awesome okay so that's it to put and for the post now let's do one to delete, okay, so doing the delete method is pretty simple, we're going to say in application dot delete, we're going to say forward slash, delete element with hyphen and then we'll just take a ID of the element actually. let's take the element id as a query parameter just to do that we'll say define remove underscore element we'll say element underscore id this will be an int and we'll make it equal to a query and we'll just add some kind of information here I'll say dot dot and to make sure this will be required, not optional and then I'll say description is equal to the id of the element to be removed and then I'll say greater than equals zero so it must be greater than zero, okay now what I can do is check if this item exists so I'll say if the item id is in inventory then we can delete it so we can do this another way actually I'll say if the item id not in inventory then what we want to do is return error id doesn't exist otherwise we'll just say dell inventory on and then item underline id is awesome so now this endpoint should be working so now let's go to our documents so let's go to clip the documents now. note that we have this endpoint to delete, it documents everything automatically, another great thing about the quick API, if we are going to create an element, we can create an element so that the element id is one, let's leave it by default, we will just run one. with name string and now let's delete this element, so the first thing we do is make sure that it exists, so the element id tests it and we get this element.
Now if we're going to delete it and all we do is test it, we pass in the element ID 1 and run this response body no, oh, because we didn't return anything from here, okay, but I should have deleted the element because now, if I go and fetch this element, I go here to get the element by id and I press run, we get an internal message. server error because well we don't have that element now let me return something here let me return you know success element deleted or something okay element deleted exclamation mark cool okay that's good now we have the update create delete and then pass name and get ID, so now we're nearing the end of this

tutorial

and I'm going to show you how you can return different status codes from these endpoints because you can see here that, for example, I'm returning like some data that says the error ID does not exist, but the status code when it returns will still be whatever the default delete status code is and that's not good now if you're not familiar with status codes every time you call an http endpoint it will return a status code saying what happened.
The default value is 200, which means ok. 201 is created. 404, as you have probably seen before, is not found. There are a lot of status codes that it doesn't have. obviously memorize them, but I'll show you how you can return as an error status code instead of just returning some data that has the same status code as the default delete status code that you know and the way you do it is upload to the quick API, import http in uppercase, exception like this and then import something called state, okay, so import both. Now I'm going to go to a place where we have some error message, so here it says data not found and instead of returning data not found when you actually want to give some kind of error message with a different status code it just raises an exception Python, so if you raise an exception and this exception needs to be an http exception, what you can do is tell the status code to say a status code like that, make it the same as whatever code you want in this case.
I can say something like 404 or I can use the status dot and then http underscore 400 or underscore 404 underscore not found I think that's what it's called, so this kind of status module here has the actual names of all these codes. of status in them yes I would prefer to write it this way when you make the status dot http underscore 404 not found this all equals 404 anyway it makes it easier to read it out loud I just want to show you that no I'm going to use the status , but you guys can use state if you want what's called an enum for each value and then you can say, let me check here in my cheat sheet.
I think it is a detail and you can give the details of why this error occurs. was returned so I can say details and say item id not found or something like that or item name not found okay so let's copy this and paste this into all the other places where we have an error so instead of generate this error say item id already exists and then it exists and I don't know what status code we should use for this. I'm just going to use 400. I think 400 means bad request. I'm not too worried about doing all this correctly.
I'm just trying to show you how we can raise these errors and then we'll raise another one here, so instead of the element not existing, we'll just do a 404, say the element id doesn't exist, and then we'll have more errors. this one too so we can copy the exact same thing so raise an http error let's copy it here and there now we're good and just to give you an idea of ​​what happens when we do this on the back end so in quick API , it's kind of waiting for one of these exceptions to be raised, when it's raised it will automatically return the equivalent type of http response so we don't have to do it manually, instead we can just raise an exception, so let's go now here. and let's update our documents.
I'm going to have to press Enter here. Okay, recharge, everything is fine. Now what I'm going to do is go get the element. Let's try to get an ID1 of the element when we do this. Oh, I forgot. It was not fixed get item by id, ok let's not do that, let's get item by name, let's search for item, search for eggs, when we do this notice we get details of item not found and our response code was 404 instead of 200 , which previously we would have done fine, so I hope that makes sense, let's try to create an element, so let's try element one, let's just run that, okay, let's try to do it again, when I try to do it again, you will .
See here we get details. The item ID already exists and we get the 400 status code telling us, "Hey, this was a bad request." You can't do that right now. If I'm going to update the item and try to update the item id 2, let's keep it that way. Again, same thing, the element id doesn't exist, we're getting the right answer, so I think that's going to conclude this video. I hope this helped you and I'll just zoom out so you can see it. This code here in some sort of screen, I hope this has given you a decent idea of ​​how to get started with a quick API.
I know I went into 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 route query and the type of arguments or parameters of the request body is very, very important and once you understand that, as you saw here, we created a pretty functional API and in not many lines of code, now obviously you will want to change this inventory. to be a real database but if you are just working on something simple and want to get it up and running quickly the quick API is a great option and yes I hope this helps you understand the framework if so make sure to leave give it a like subscribe to the channel I will see you in another youtube video

If you have any copyright issue, please Contact