YTread Logo
YTread Logo

Python REST API Tutorial - Building a Flask REST API

Jun 07, 2021
Hello everyone and welcome back to the YouTube video, so in today's video what we will do is create a RESTful API in Python using the module called

flask

now for anyone who is not familiar with

flask

and can not only create websites with Python using flask, but you can also create

rest

APIs, which is what we will do in this video. It's really known for creating web microservices because it's a very lightweight module, it doesn't come with a ton of stuff in the box, but for our purpose. It's perfect because there is a lot less configuration we need to do and it's really fast, just a few lines of code to initialize flask and start using it to create an API now for anyone who is not familiar with the term

rest

or the term API, I will explain it quickly. define them so that rest means transfer of representational state.
python rest api tutorial   building a flask rest api
You'll see why that's important in a second and API stands for application programming interface. Basically what a REST API is is a way for other programs or applications to manipulate, query, update or delete. or whatever information is, it is a way of handling some type of data in a structured format. What I mean by this is that we essentially set up this API that has a bunch of endpoints, now these endpoints are essentially almost like commands or you. You can think of them as just requests and when this endpoint is reached, when someone reaches that endpoint, they go to it, connect and send a request to that endpoint, that endpoint will return a response based on the request that was reached. gave, for example.
python rest api tutorial   building a flask rest api

More Interesting Facts About,

python rest api tutorial building a flask rest api...

If the request was to give me all the views on a specific video then the response would be the number of views there were on that video, let's say the video doesn't exist then maybe the response would be something like 404, you don't know. I found it okay, we couldn't find what you were looking for, so it's just a very basic example. The reason I mention this is because what we're actually going to create in this video is some sort of mock YouTube API. Very minimal, obviously, we won't have all the features of YouTube. We will deal with channels and videos and essentially create some kind of REST API that can not only create new videos, but can also give us information about videos and can delete videos. we can update them and link those videos to channels, so we'll start by

building

a very basic API that just does something like return information to us and then we'll create one that actually allows us to create new information and update information. put that into some kind of database, then we'll deal with custom objects and while this video is going to be long, it'll pretty much cover everything you need to know to create a fully functional web service and a restful API, so with that being said, Let's go ahead and get started, so before we can start writing any code, we need to install some requirements in our Python environment.
python rest api tutorial   building a flask rest api
Now, if you have experience with this, I'll assume you already know what to do. I have a txt of requirements. file in the description right now, you can go ahead and download it and just install it, but for those of you who haven't used pip before or just don't know what I'm talking about, essentially what we need to do is install some Python modules and we do that by through a command line tool called pip. Now, by default, pip should be installed on your system and you should be able to use it. You can use pip by typing pip in your terminal or command prompt. when typing pip 3 now for some reason this doesn't work, first make sure you have

python

installed and if you have

python

installed and it doesn't work you need to configure pip on your system for it to work properly so i will leave a link in the description, as well as a card in the top right corner follow that video which is titled how to install pi game but it will show you how to fix your pip now once it's working we need to install three things we need. install flask flask restful and the request module now to make this easy for all of us what I would like you to do is go to the description and click on the link that says download txt requirements or will there be something that says txt requirements that should download this text file for you and I want you to place it in the same location where you will write your Python code, in some kind of folder or area that you can find easily, maybe on your desktop or something, so once you have the requirements of this dot txt file to have this content here somewhere on your desktop or somewhere you can find it, what I want you to do is navigate to it from your Windows Explorer or from Mac OS.
python rest api tutorial   building a flask rest api
So I'll say both ways here, but I'm in the wind so I'm going to illustrate how to do this so you can see that I've now navigated to the folder that has my txt requirements, now there's a shortcut to open. the command prompt in this directory is to type CMD, it types it in this little bar at the top, so delete everything there and type CMD and notice that when CMD opens, the path that I'm highlighting here will be the path to the txt of requirements. file, this is the goal, you just need to make sure this path matches.
You can also use something called change directory, so change directory will allow you to select the folder or location you want to move to, so if I say CD and then type flask rest api

tutorial

like that. I have overcome those options by pressing tab. You can see that it will move me to that folder and now I will be in the correct location, so make sure this matches if you are on Mac. and you have navigated to the correct location, what you can do, I think, is right click and click open terminal or something like that and then you should be in the right location to be able to do this; otherwise just use change directory from opening. terminal to enter the correct directory where your requirements are, not the txt file, and then you should be good to go, so now what we are going to do is type pip or pip 3 depending on whether you are on Mac, Linux or Windows and then type installation from pip: are and then the requirements dot txt, so this is the command you might need to change this back to pip 3 if you're on Mac or Linux and then go ahead and hit enter.
What this will do is take all the lines I have inside a requirements txt and automatically install that module into your Python environment this way we're all on the same page, we're using the same versions and hopefully everything should be okay, anyway, once I've done that, we'll be Okay, let's go to an empty Python file, you can create one. I'm going to call my main top PI and let's start writing some code so make sure you have them all installed again that's flask restful flask and the request module ok so the first thing we're going to do is say from flask import flask with F capital letter and then we will say from flask underline restful imports API and import resources now these are the two main things that we need to use are the two main modules that we will use here, we will import a few other things, but the first thing we need to do is create an application inside flask , so this is common, this is what you normally do when you create a new flask app, you say app equals flask and then you underline the underscore name, you underline the underscore, so there's two hundred scores in there, make sure not to miss that and then next we'll write API equals API and put in the application.
In here, this is pretty much saying that we're going to wrap our application in an API and this just initializes the fact that we're using a rest API once we've done that, what we're actually going to do is go to the end of our program and we'll save the underscore, the name of the underscore, the underscore, the underscore equals and then in double quotes, the underscore, the underscore, the underscore, the underscore, then we'll say app dot run debug equals true, this is going to actually start our server and start our flask application and the fact that debug equals true will say that this is in debug mode, so we'll see all of that output and any information from record, so if something goes wrong, we'll know why.
If you're ever running this in a production environment, don't run it with debug equals true, this is only when you're running in a development environment and testing things like we are now, so once we've done that . I'm just going to open a command prompt window here. I'm going to go and actually run this main Pi dot application and make sure it's working. Now you can run this from wherever you want, but I'm just going to run mine using Python main dot PI. I'm doing this from the command line and you can see I'm in the right directory where that made up high script is, so running Python main top.
I'm actually going to use Python to run that file. Again, if you're on Mac or Linux, this could be Python 3, it really depends, so now we can see that it says running on HTTP 1 to 700 1 colon 5000, so this is actually the URL that our server or our API is currently running, so this means that every time we send a request, we will send it to this location right here and then anything else that goes after the slash, so this is just the location of your localhost . You can change this if you want, but make sure that this works first and that We should be ready to go, so now that it's working, what we're going to do is we're going to go ahead and actually create our first resource, which we call, within this API.
This is quite easy to do. What we're going to do is create a class, we're going to call this class whatever we want, whatever makes sense, whatever information it returns to us, and in this case I'm just going to call mine HelloWorld. Now this is just a basic example. It will get more complicated later, but within HelloWorld what we will do is inherit from the resource. Basically what this says is that we are going to create a class that is a resource and this resource will have a few different methods. that we can override and that will allow us to do things like handle a get request handle a put request handle a delete request that's what we write here, so don't worry if you're not familiar with the classes, but the idea is we define what we call get inside of here, so I can define get like that and I can put I here and then this is what will happen when a get request is sent to a certain URL which we'll talk about in a second. anyway we're going to define enter here, all I'm going to do now is return a Python dictionary that just says hello world inside of it like this, again, this may not be completely valid, but that's totally fine, it's just for this one.
For example, what I did was create a resource called Hello world. We've overridden the get method, which means this is what will happen when we send a URL, our Sunday Get requests to read at a specific URL and then when that happens, I'm going to return the information Hello world, so let me go here now and what I'm going to do is register this as a resource, so I'm going to say API dot add resource and then inside here resource I'm going to put the name of the class that I want to add, so essentially what I'm saying is that, given that this is a resource, let's add this to the API and make it accessible through what URL, so now I'm just going to put a forward slash that just means default URL, but let's say we only want to access this when the user types hello world , send a request to hello world, so I would use hello world as my endpoint here, so essentially we're determining what the root of this resource is going to be.
How do we find this resource when we submit a request? You know the server that we're running on, that's what we're talking about here, that's what we've done, we've said dot API add HelloWorld resource and we've said it will be accessible in slash hello world, what that means is that if we send a get request for slash hello world should return the information hello world so to really test what I'm going to do is create a new file and I'm going to call this test dot py go ahead and do this too if you want you can also do it in an interactive Python console, but since we're going to do this multiple times, I'll do it in its new format. file and what I'm going to do inside here is send a request, so I'm going to import the Python request module, this allows us to send the post request to it, make the request, get the request, whatever it is and inside here I am .
First of all, we're going to define what our base URL is going to be, which is 80 HTTP colon slash 127.0.0.1 colon slash 5000 and that's my base URL, so essentially that's the location of the API, which is the server on which it is executed and recovery. which we got because we were looking here and it said run on this is what you want to put where you are, where I'm putting the base here, that's essentially what we want now, what I'm going to do is say the response is equal request dot get and inside here I'm going to put the base URL plus hello world essentially what I'm saying is I want to send aget request to the base url plus that so we're going to send it to that slash hello world and then I want to take that response and what I wanted to do is I actually want to print the JSON response dot now the reason I have to do the dot JSON is simply because I need this to not look like a response object and there will actually be some kind of information, so this dot JSON method will do that for us, so let's go ahead and see what happens when we run test stop.
Hi, the way we're going to do it is we're just going to run the command prompt window here, so I'm going to start by running our API, we're running our flask server and then I'm going to go ahead and run this dot PI test and I'll show you what happens and it looks like We have had an error here the typeset object is not JSON serializable. I know the problem here, that was my problem, I feel it within this, here we are. What I'm going to do is, instead of just having a hello world, we're going to say Dad: hello world, so I just need to do a key-value pair here, whether you come back from the get request.
I thought we would have to do that, but I wanted to. To just try it with everyone, so anyway we're going to try it now. I was watching the video while editing it and realized I'd missed a pretty important explanation, so I wanted to include it here, essentially what I want to say. is that every time we return some type of information from our API we must ensure that the information is serializable. That's a big word, a lot of people probably don't understand what it means, but they'll see it when it happens. information back or return information sorry I'm doing it inside a Python dictionary now the reason for this is because this represents what we call a JSON format now JSON is literally Python dictionaries you have keys and you have value so it would have something like data that could store another dictionary and then inside here it could have a similar name and that stores Timm whatever.
This is like a JSON format and essentially we're going to return JSON serializable objects, so what we need to do is make sure that we return Python dictionaries or something else that is serializable so you understand and realize that I can't just return the string hello world, actually that will probably work, but there are some things that I just can't return from my API or that will give me all kinds of errors because they are not serializable to JSON, so just make sure that when you return something from your REST API be serializable to JSON, if you don't understand what that means you can look at that. above, but the general rule is that if you want it to work, just use a Python dictionary like this, create some key and then have some value and you should be good to go.
My apologies for not having it in the original video, but I hope that clears it up. For any of you wondering as we move forward, let's come back here. I think the server is still running and by the way, when you run the server in debug mode, when you save it, it updates automatically, that's why it happens. Testing Python on pi and now we'll see what we actually get when we refresh this so we can see that what it actually returned to us here is hello world data and it showed us that a get request was sent to trim hello world. and 200, which means it's fine, so when you see a status of 200, that means everything was fine, nothing failed.
Now I can do this as many times as I want. I can keep it running these requests and every time I run Python it testifies that we are. You will get a result that says data Hello world, perfect, here we go, so those are the basics of creating a flask API, of course, we will continue, but this is how you create a resource, go ahead, define a resource like this, override any method. you want it to happen on this resource, so in this case we want a get method and that's it, when you've sent a get request, it's going to return whatever you go ahead and put here.
Now let me retest the operation here and I want to show you what happens when I send a post request instead of a get request, so let's go back to our command prompts, the server is still running, as you can see there. I'm going to run the Python test, stop and look at what it says here. This message, this method is not allowed for the requested URL, so we actually got an error that was handled automatically by flask telling us, hey, no, you can't do that. We don't have an overridden post method here in our main DUP.
Hello. Sorry on our hello world resource, so that doesn't work, but if I go ahead here and say define post and put it in and we return this same information here, it's actually returned data and we'll just say published like this and let's see what happens now when we run this, so let's back up the Python tests. Hello, there, we post the data, so when we override the correct method and use the correct method, we are fine and that works fine, so now. What we're going to do is take care of storing data on the server and understand how we can pass information through the request because it's not extremely useful to just retrieve a dictionary like this that just says data and then any information.
Here what we probably want to do is return specific information or we want them to request something specific. They probably won't just send a general request that can give them everything they want, so what I'll show you. Now this is how we can pass arguments or pass some kind of parameters through the request URL, so if I look at the forward slash here Hello world, what I can actually do is a parameter that I want to be passed to me now to do this, I do it. What you need to do is use these angle brackets like the ones I have here to define the type of parameter you want to include in this case, I'm going to say string, but you could do int like that if you wanted.
I think you can also do boolean, but I'm going to put in Slyke this or something, not a string that defines that hey, I want this parameter to be a string. I'm going to put a colon and then I'm going to define the name of this parameter, which in this case is just I'm going to say the name, what it basically says is that I want the user to type a string after Hello world. We're going to pass that into our request here, so in this case I'm going to go and say a name like this and what that means is that now within this get request I'll be able to access whatever name they've typed in here and I can do something specific with that , so now all I'm going to do is return that name to you just to show it.
You know how this works, but the idea is that we can create parameters and technically I can create another parameter if I wanted to, go ahead and do int and just say you know, try or something and I'll actually show you how it works. works now we have a name and we have test and I'll just go and say test and we'll just put tests like this and then the data we'll actually just put the name and this way we can see what these two are. are so now if I want to send a request to hello world I need to pass not only a name but I also need to pass some numbers for testing so I'm just going to go Tim and I'm going to pass nineteen just with my name and my age it's okay, so let's go ahead and do that and run these two things now and see how it works so we can see that the server is automatically updated because it's in debug mode so I don't need to run it again.
Now I'm going to go to the Python test stop. I just update that there and, oops, we can't use a post request anymore. We need to use a get request. My apologies for that, so let's come back here and run this one more time. python test op pi we're called Tim test 19 because that's the information that we sent and that was the information that we received, so those are the basics of creating parameters inside of here again. The reason we could do it is that we can have the the user asks for a specific one, so now they will pass hello world, let's keep it in name for now, we don't need anything else and what I'll do is create an object up here that says names, it's okay, so I'm going to say names alike and we're just going to make a dictionary and what we're going to have the user do now is when they send us a name, we're going to return any information related to the name that they asked for, so let me come in here and let me go Tim and let's go: and let's do another bit of information here, we'll say 19 years old, we'll say male gender and then what What we do is argue that that's not what he wanted, we'll do another one here, so let's say Tim will say that Bill He's turning 70 and we're going to go back to using the masculine gender, so what I'm doing is just putting some information in there. from a dictionary here that we can access and now when they say get, what I'm actually going to do is return names like that, so now we're going to take whatever names they pass in and give them related information. to that name, so let's go to the tests now, let's change this dust to be Tim and now let's try this and see if it works, so if we go here, let's go.
The male Python name is not defined. Oops I need to put that in a chain my bad guys so man it needs to go in quotes like this okay now we should be ready to go let's see if the flask server is working okay we're good let's run the test on high and there we go, we get information for he was 19 years old, male gender, now let's go ahead and change the name here and set up a Tim to be built. Oops, it's not null. I want it to be built, so let's run this now and we can see that we are 70 years old, male gender, so that's the basics of how it works in terms of passing parameters and returning information, now let's start creating what was speaking before, which is this video system or this type of YouTube program or API or whatever you want to call it. so set up hello world, now what I'm going to do is create another class and I'm going to call this class video, this will inherit from the resource again and we'll have an entry here that has an underscore ID of self and a video.
Now what I'm going to do is instead of names I'm going to go here. I'm going to say the videos are the same and we're going to make some sort of empty dictionary like this that's going to store all of our videos now what I'm going to do is I'm going to say return video ID videos so essentially when you send a get request to whatever URL we're at point to define here, you will get any information about the video that the video has. ID you requested, so what should we do? We need to add a resource to our API, so we'll say API add resource, the resource will be video and the key will be slash video slash int: video.
ID, here we go, so now whenever we send information to this request, we need to pass a video ID and we'll do something with that now instead of just doing it, although what I really wanted is I want to open a path for us. to create a new video, so we're going to say "put it here", so let's define "put", we're also going to say "self-id" and "video underline" and now what we're going to do is create a video inside this says now, how are we going to do that? What information do we need for a video?
First of all, that's the first thing we need to define. Okay, when we make a new video. What do we need about that video? having something like views, likes, dislikes, is that information that we want to store, do you want to store the age, the time that all of that was uploaded, okay, how do we do that? Okay, this is where we'll start talking. something called argument parsers now is the first thing I'm going to do here, so I'm going to go ahead and write a postback so we have something to do here, but we need a way to essentially create a new video, so we're.
We're going to make them have to pass some information that's not actually inside here, so not inside the URL but inside the data, so when you send a request, let's go to our test script here, what you can actually do is If the ice changes to say a sales request. I can pass data in the form of, for example, JSON or some other format here that will actually be sent along with my request, so instead of just having all the information we want stored directly within the URL, which anyone can type . from see and look, we can send information through data, so I could send something like like 10 like this and essentially I just want to show you the way that we can get data from a request like this correctly, so if I'm sending like 10 How do I get this information on my application on this side?
Well, the way to do it first is by importing the request up here, so from flask, excuse me, import the comma request from flask now the request is the request object that can be used inside the resource and Basically, what it will do is provide us with that information so that you can provide us with things like any of the data that was submitted here. There are also other things we can access on demand, such as the method, for example, place my request pointguy and me. I think the method will tell us that this was a sale because while we're inside the sales class we're inside the sales method, sorry, but anyway, if I want to see the data that was sent, what I'll do here is just print. and we'll just say request dot form now that the data that we send here comes in what's known as a form and we can access the likes.
We can access any of the other keys here by doing something like request dot form and then putting like here. Now what that's going to do is give us the value 10 because we submitted a form that has the like key associated with the value 10, so I hope that makes sense, but I'm just going to print stop request forms. You can see what it looks like, I mean you. I can get an idea of ​​how this information is sent. This is the server to my left. I'm going to run this. Sometimes I have to click here to make it work and we can see an odd mutable multi, yes, immutable. dict and here comes the comma 10 of like, so obviously it's not a format that most of us are familiar with, but it stores that information and again, if you wanted to, you could use like, okay, but in reality is much easier. way to do this instead of using requests, in fact flask restful comes integrated with something called a request parser which essentially makes sure that when we send a request we pass the information that we need with that request, so what we can do is we can reality say video underscore put underscore.
I'm just going to call this arguments equals requests a parser like that point and then in this case it's requests parser now we just put square brackets like this here to create an instance of that, but what this says is that we're we're going to create a new request parser object and what this request parser object will do is automatically parse the request that is sent and make sure that it fits the kind of guidelines that we're about to define here and that it has the correct information if it does, It will actually allow us to get all that information very easily using a method called parse args.
You'll see it in a second, but follow me here. The idea is to say every time we want to create a new video we want to have three different fields, so we want to have likes, we want to have the name of the video and then maybe we want to have I don't know what else we had here, the views, how many views are they? . In that video, well, if we want to make sure that these three pieces of data are sent to us, we need some way to validate that right, so this parsing request here that we're using, video put args is going to do that for us, so what?
What we do is logo video put arguments dot add argument and what this says is this is one more thing we want this is something we have to send with it so what we're going to do is not put the name of the argument which will essentially be the key that needs to be sent, we're going to put in a name, we're going to put in the type that we want this argument to be, in this case I want the name of the video to be a string, so I'm going to put in STR, we're just writing Python data types here so that can do it in boolean string, etc. and then you can put in a health value and what the health value says is what we need to show the sender if they don't send.
Use this name argument, so essentially it's like an error message that we're going to put in here, so we're just going to say that this is the name of the video, so this will tell us if you didn't submit the name, this argument is. the name of the video that needs to be sent and flask will automatically handle sending air requests to the sender if that happens if the request parser doesn't find the arguments that we need, so what I'm going to do now is I'm just going to copy this and I'm just going to paste it two times more because what we're going to do is we're now going to have names, sorry, not names, not names, views and likes as required arguments and now these will be both ins and us.
We're just going to name a video, we're going to say video views and I'm just going to say Video Likes Video Views Video Likes Yeah, that makes enough sense to me, okay, now we have a request parser. which has these three arguments. that is required to be sent, these are the types of arguments and these are the helper strings that will appear if we do not send that valid argument, so now inside what I'm going to do is say args. is the same and in this case we are going to do video put args dot parse args now this will get all these arguments that is what args means arguments from here and if they are not there, if they were not sent I will automatically send an error message so what I can do now is just print arguments or just send a response that is video id: arguments.
I won't be able to see what the arguments actually are, yeah, so it should be fine for now, we'll add it to the videos later, but I just want to make sure this works for us before we do anything else, so now when we ship one request, I'll leave it at that for now. I'll show you what happens when we send an invalid one and then I'll send a valid one so you notice that we don't send anything to do with views or the name of the video, we just have likes, so I loop. I could open this, okay, let's take a look at this now, so the Python test stops.
Hello.What happened? We have a lot of bugs. Well, that's because we didn't ship the right thing in the first place. We closed by force, let me send that one more. Once there we go well, now we get a name and no view, no one likes it. Tenth, okay, sorry, I don't know what happened there. I think it's just because the server needs to be updated, but the idea is that this was the response we got. when we didn't send the name and views now, the reason it didn't fail is because we didn't make these arguments necessary, which I'll show you how to do in a second, but notice that the argument parser created them automatically. none because we didn't send anything with them and it got 10 likes, so our API response here was the video id arguments inside a dictionary and the arguments, of course, were a dictionary that had those arguments.
Now let's say we really want this to fail when we don't send the correct arguments, then what we need to do is make this required so that you can say required equals true inside all of these additional arguments and this will ensure that now, instead of sending that valid response back with none as the key for everyone is known as the value of all those keys, actually it will just fail or show us an error message, so let's run this now and notice that we receive the name of the message, name from a video, so this tells us more or less Hey, you know this was the argument that you sent, this was not valid, right, this just didn't happen and, in fact, within this health aid chain, I'm sorry , what we should probably do is say that the video name is required, just to make sure. who really understand that, but anyway you get the point, he sent us a message that said, Hello, you know, name, this is the key or the argument that we're looking for and this was the help string associated with it and we would do it.
I wouldn't have created a new video if that had happened, anyway, that's the basics, now that we understand how it works, let's start adding videos and then we can get videos to make this work a little more and then we'll be. We're talking about deleting videos and adding some other things too, so the first thing we're going to do here is add a new video from the drop request, so let's say the arguments are valid, we don't get it. If we know that an error message appears, what we are going to do is save videos. The underscore ID of the video is equal to arcs, since args is its own dictionary, it's totally fine to do that and now what we can just return is just ID whenever we actually want here, so I'm just going to return the underscore ID. below the video and what I'm going to return next to this is actually a code.
So what you can do if you want to return a specific status code to the person submitting the request is inside the return statement, after returning the data you want you can simply return some wrap, so 201 means created, so I'm going to send 201 as a response so you can see that, hey, you know this is created and it's working fine. You don't have to send them by default, it sends what is known as 200, which is the one that indicates OK, which simply means that you know that nothing is broken, but there are many other status codes that you can send depending on what what you are doing.
I'm going to send one to show the person that it was created and let's go ahead and test this now because now we can use a get and a put request and we can see how they work together, so what am I going to do? i.e. the response is equal to the request, stop, it will print that and then I'll just copy this again and put an entry in the middle so we can pause it and I can press ENTER first and now I'm going to actually send a get request and I'll look for slash one of the video, so the idea here is what I've done is I've said whatever video ID they pass here in the drop request, like the actual name you want to call. as an argument or as a parameter, whatever is after this slash, we're going to make it the video id, so it's going to be the key inside this dictionary and we're going to associate it with the arguments that are passed in as some kind of right data. that was submitted and then that way we can give them back the ID of the video and since they created it, they wouldn't know what the ideas of that video are, so anyway, okay, we'll just do that and let's go. and take a look at this, okay, now the service should be running, we will run python tests on top, we get the name of the message, a video is required, I forgot, that's a good job, we have those messages because I need to add a name I'll just put it as Tim and then we need to add views which, as you know, we'll put a hundred thousand for now, so let me update this one more time.
Okay, wow! The server crashed. They let me rerun this because The key didn't exist okay but let's do the Python test Hi, now we can see the name Tim views 100,000 likes 10 and I'll press enter and we'll get the name Tim views 1,000,000 likes 10 the reason that's significant is because I sent a get request request for ID 1 and it returned us everything that was stored inside the videos that had ID 1, so I'm sure most of it That's what's working now. The next thing I want to do is fix this bug that I just came across here, there would be a lot of code that was going on in this key 1 error and I want to make sure that we don't actually fail if we request a video whose ID doesn't exist correctly because if try to access video ID 1 from videos and it is not there, then of course our program will fail, so how can we prevent it?
Well, what I can actually do is define a function that I can say cancel if in its score the video underlines the ID. Does not exist, this is a long name for the function, you can use whatever you want, but I will say cancel if the video ID does not exist. I'll put the video ID here and what I'll say is if the video ID doesn't exist. in videos, what is the variable that we are using to store the videos, so I will say abort like this and what I am going to do now is import the abort from the flask.
The restorative abort will essentially send an error message saying whatever you put here. so we're going to say that the video id is not a valid dump like that, so essentially this will just abort, so whenever you see the abort function like this, whenever it's called, it will immediately return a response that says " “Hey, this lockdown, this didn’t work.” So we can call abort like this and that return statement will be skipped, so keep that in mind. So what I'm going to do now is inside guest. I'm going to call our guest inside get. I'm going to call for an abortion, yes.
The video ID does not exist and then inside of here I'm just going to put in the video ID and that should be fine so this is going to make sure that the video ID exists before we actually go ahead and do that return so that we can avoid crashing the system. program, so let's go back to the server now and our test script and let's go and test, let's get rid of this first here because we don't need we can get rid of the entry and let's try to look for a video ID 6 and see what happens now if we do that.
Obviously video ID 6 doesn't exist, so if I run the Python op pi test, what happened here? We have some kind of error. Let me take a look here, okay? I noticed the error here. I forgot that I actually need to send what's called a status here, so before I can send the message, which is this, I'm going to define by saying message equals this is correct, now we need to send a status. code, so if we abort we must send a status code. 404 means "I couldn't find you" and you see "404 page not found", we will say that the video of themessage is invalid or we could say "we couldn't find the video now" to give you an example of some more status codes, there is a 409 status code which means the video already exists or what you like already exists.
I'm just using video because that's our example, there are many other status codes and if you want to know about them, I recommend you look them up, so anyway let's run this one more time. It is common to make some mistakes here. Go to the Python test on pi and now we get the message Could not find video status code 404, which we can see here, so that's okay. Now that we have the video working, the next thing I want to do is implement another method to delete a video and I also want to make sure that we don't create a video that already exists, so let's go with the jump. video first I'm just going to define delete, note that my methods name matches the HTTP methods I'm adapting so we need to delete, you don't have to use them for what they're actually meant to do if that makes sense but it's a Common practice is to use put to create something, use delete to delete something, and use get to return something.
There's also a patch called that we'll use later that allows you to update something, so I'm going to say delete self and then what we're going to do here is we're going to say video underscore ID and what we're going to do is make sure that this exists, like this which first I'll create another method here and I'll say define abort underscore if underscore exists and inside here I'll say video underscore ID. I'm going to say if the video ID in the videos will be cancelled. We're going to abort with a 409 status code which means this already exists.
We're going to say that the message is the same as the video that already exists with that ID and we'll do a dot, dot, dot for that too, oh, now what I'm going to do is inside put, sorry, I'm going to put a yes button. the video exists. cancel if the video exists like this we'll pass in the video ID this is just to make sure that we don't create a video that already exists so we'll cancel if it exists and then inside delete I'll say cancel if the video doesn't exist if I can find where was that cancel underline if video id does not exist video id then if it exists let's add Dell videos video id and then we can simply return this comma 204 204 means successfully deleted so this is just a string in white.
I don't want any messages. I just want to send a status code for this essentially saying Hello, that worked. you were able to delete this, okay, so now that we know things look pretty good, let's do some testing here with a few different requests and just make sure everything looks good, so let's do a response request here. Upload, place the video. with ID come on three we can do that okay and let's actually just send a bunch of requests here that have different information so I'm just going to say data equals data actually equals a list and then inside this list I'm We're just going to fill in a bunch of different information here and make a bunch of videos so we can do some more interesting queries.
Well wow, I wanted to get in there just trying to get this list somewhat organized so we can. read this a little easier okay so tab here we go and we're only going to do three videos for now so like there's no 78 names come on Joe I mean name this should really be the name of the video , let's see how to make a REST API. views, well hopefully this will get a lot more likes and then we'll get to the views, you know, 80k or something and then we can leave this Tim the same, but let's make him have a different number of views, let's make let there be two. thousand, let's give it 35 likes.
Now what I'm going to do is just send out a bunch of requests. I'll say I'm within range. I guess this will be the data Len that we'll say and just use. all this is fine, then the response is equal to the request, put the slash of the base video plus the string. Because this is going to be whatever this is, that's going to be the ID that we're going to pass in and then instead we're going to go to the data. Awesome, I'll print my JSON dot response. and at the end, here we'll go through and delete one or two of them, so we'll say the response is equal to the request get, let's go to base plus and instead of get, this is actually going to delete, it's going to base plus slash video diagonal 0, I know. that will be there and then let's print the response JSON so let's print the response JSON dot okay so what I'm doing is I'm just sending a bunch of requests with different information that's stored here and delete one of them and I'm going to try to get to video two and let's see how it looks.
I'll add some entries here, okay, so run. I think this has been updated. Yes, the server is working now. Let's run tests on high and see what we get. Okay, so first. i got all this successfully and then something happened expecting value one per line column one. I can't see exactly what that is because I have to make a JSON response from something that doesn't have any JSON data attached to it, so I'm sorry. about that guys, essentially the reason was that I got that error because on this side I had a JSON dot after my response, but notice that when I have a request, that's the delete method, we don't actually return anything that's of type a JSON serializable object we just return a blank string, which means that we will not be valid to be able to use dot JSON, so we just have to use response, so now let's try this one more time, first let's run this server again, just delete. the memory there, so python main dot pi and then we'll go to python test dot pi.
Notice this works fine let me hit enter we get response 204 which works fine and then we name Tim views 2000 likes 35 when we query ID I think it was 2 or 3 or something like that anyway you get the point it works correctly and our API works pretty well, so the next thing I'm going to show you how to do now is to add this to a real database, instead of just using memory. What are we using now in the videos? How can we actually get this to be stored in a persistent database? We're just going to use a SQL alchemy flask with I think it's a SQLite database so I'm going to configure a little bit of things that will be fine again so now we're going to add the database so to do that what we have What to do is first install another module called flask SQL alchemy, this just gives us a really nice interface for working with databases. something similar to what Django uses as well and it is a very popular way for databases inside flask now if she installed using the dot txt requirements method, she did the installation with pip; our requirements txt already has it installed if it didn't then you will need to go back to the command prompt you need to type pip install flask - SQL alchemy like this I think that's how it is written so SQL alchemy yes it should be correct so pip install flask SQL alchemy make sure it is installed on your system again that could be pip3 depending on what system you are on and once you have it we should be ready to go and initialize this database so inside from our code we are going to say from flask SQL alchemy import SQL alchemy then We are going to say that DB means database equals SQL Alchemy application so again the same thing we did with the API here just wrap the application and then what What we're going to do before this is configure it, so let's go. to say app dot config so we're changing the configuration settings we're going to add this one here which is alchemy SQL like a box or you can spell it like this though in all caps like this alchemy and then underline the database underline the URI so essentially Let's define what we want the location of our database to be, where we want it to be and the way it works is by doing a colon SQLite, three slashes like this and then the name of the database, so we'll say dot database.
DB, so essentially we're saying that the configuration here we're going to make the SQL Alchemy database URI equal to and then whatever the name of the database is, now say you want to save it inside a folder inside of the route you want. Currently, I would do something like the TMP slash database and store it in a temporary folder, assuming you created one inside your current directory. This is known as a relative path, which means it creates it based on the current path. So when we say database dot DB, we will simply create a DB database file in the same directory as our current script.
After that, what we will do is write DB to create everything. Now what is this going to do? Actually what we do is we create the database now, we only do this once, so after we run this script for the first time and it actually creates and initializes the database, we won't do what it's called, we won't do this again never more. now the reason for this is because once we create the database we don't want to reinitialize it because if we do we will override the tables or the data that we already have there, now the only thing is that we don't want to do this until we have defined the models that we want have in our database, so what I'm going to do here is I'm going to start coding a mall to store videos, so I'm going to say class video model this.
It's going to inherit from the model that I'm going to import here with a capital letter, so from asking sqlalchemy to import a model like that and then what actually sorry? What am I saying? Don't care about the model. What I'm going to do here is say DB dot. model, so the bad thing is that we are not going to import anything here, we are just going to use the database that we created here, which means database point model, now what we can do here is define all the fields that we want to have inside . of our video model so the first thing I'm going to do is have ID so I want to store some kind of ID in my video model which will obviously be the video ID so I'm going to say DB dot column like that and then inside here I will say DB integer because it will be an int value and we will say primary key so it is equal to trick.
Now I'm not going to go over too many things related to the database, but essentially a primary key means that this is a unique identifier, so it means that this ID will be different for each video that we store in this database, so The thing to keep in mind next is to say that the name is equal to a database column. it's just a column of information, so within a database we have multiple columns for each model, we have tables within those tables, we have columns, each row is an entry or an object type of that table, if that has some sense. know the model whatever you want to call it, so here we'll say DB and this will be a DB string.
We'll put in how many characters we want to potentially have in this string. I think the maximum number of characters for a YouTube video is a hundred, so let's go with a hundred and then we'll say a single note that's not true. We will say that nullable is equal to false. Now the reason we do this is essentially to say that this field must have some information that we never have. We'll have a YouTube video that doesn't have some kind of name, so if you set nillable to true, that means you can insert something into this model that doesn't have a name, but we want to always have a name.
Serena says "nillable equals" false the next thing we need after the name is we need the views so this will be very similar to the first false columns we will say views equals the db dot column this will be a dot db integer, this will be nullable, equals false, We'll copy this again for the likes, so we'll say like equals DB column DB non recognizable integer equals false and finally we'll define a wrapper method so that if let's print this actually get something that's somewhat valid. define underscore underscore wrapper underscore punctuation scrander we're going to put in a self and what we're going to do is return an F string for the way this F string only works in 3.6 and above, so if you're not on 3.6 and Don't do what I'm doing here just try to find your own way.
I'm going to say video and inside here I'm going to say name equals name. I'm going to say views equals views and I'm going to say likes equals likes, this essentially every time you have a string F and you put something inside the curly braces, it will actually print the value of that variable or expression inside the curly braces, so we'll get name equals and whatever name you use is equal to whatever the views are and we can remove this just to make it a little bit easier to read okay this container also just happens when you decide to print the representation of this object or decide to see it internally or will you ever decide to do so.
This will just give you a string representation so we can see what all of these videos look like. Now that we have a video model, we can go ahead and do D. create right after we create this model and that will create a database for us that has this model in it, so what we're going to do is run our script here, so I'll say Python main. dot PI and there we go, createthat model for us and we should be ready to move on with that, so after we've done that we'll make sure to remove DV dot create all because we don't want to do that. that a second time or that will override the data in our database and that should be pretty much it now that we have the database configured and created and we are ready to start working with it now to create a new object in the database .
Really easy, what you do is just create a new instance of this class that has all the valid stuff that we need and then just commit it to the session. I think I'll show you how we do it in just a second, but I'm going to start by deleting some of this stuff, so first of all I'm going to delete videos like that. I'm going to remove this abort right here and we'll start changing some of this code now so that it actually works persistently with the database. So the first thing we want to do is, instead of it getting like this, what we're going to do instead of returning the video ID of the sorry videos, we're going to have to query the database and return something that fits the query that we have, so we're going to say that the result is equal to, in this case we're going to go to the video model query dot get and then inside of here we're going to say that ID is equal to video ID, so essentially we're going to look for some models that you already know , some rows. video inside this video model that has the ID equal to the video ID and then we're going to return it to the user.
This is where it gets a little complicated, if I want to return this result, well this result is actually going to be an instance of this class now I know I'm hitting databases and there's actually a lot to explain with flask alchemy SQL, but essentially the way this works is that when you query this video model it will give you instances of this video model that match whatever you put inside here, so I put ID equal to video ID. I will get all the videos that have this ID and since I am only getting it will return only one but it will be an instance so how can I? actually serialize that instance and return it so that my test script here that is looking for a response can read that information well and this is where we use something called resource fields and group with now a resource field is essentially a way to define how it is you need to serialize an object, so what I'm going to do here is say that the resource underscore fields are equal and what I'm going to do is define what I want it to be in these fields, so I'm going to say I D and then I'm going to go: fields, dot string like that and now I'm going to go up to flask restful.
I'm going to import fields and I'm going to import a decorator called Marshall underlined with. I'll define what they do in just a second, but inside. of dot string fields what I'm going to do is get rid of these square brackets and just leave it like that, what I'm basically doing is saying, "Okay, I want to make this dictionary here define the fields of this video model that I want to return if I return a specific object. It seems confusing. I have to keep it." code to make more sense, but follow me. I'm trying to say that this ID field here, which is the name I'm putting in here, is equal to the stop string of the field, so that's the type of the field which is next.
What I'm going to do is say the name field, which is another one that I want to see. I'm going to say that the name is equal to the intensity of the fields points and, sorry, the id should be an integer number of fields points, my mistake on that name. it's going to be a field string and then the views and likes are going to be the same thing it's going to be integer dot fields, integer trick field and then we're going to go to likes it's integer dot fields awesome so now we have all the fields defined .
We also have our ID and we should be ready to start using this. So what do we do when we really want to grab some object? Because the result will be an object when we have a video model query that gives us an object of a video instance. model, so what I'm going to do is this, I'm going to say in Marshall width and inside here I'm going to put resource fields. Now what this essentially says is that when we return let's take this return value and serialize it using these fields. so we'll assume we have a name of IDs views and likes in the instance that's returned, it'll take those fields and essentially serialize them into this JSON format that can be returned, so we'll create a dictionary that looks like ID and then what whether the ID is there and the name and whatever is there and the views and likes and all that is what this decorator is doing and you can put that on top of any method inside here inside your class that you want. go back and serialize the object, so let's try that, now I'll get rid of put.
Actually, we won't get rid of puts. We'll just modify this slightly, so now inside put, what I'll do is show you. how can we create a new object in the database, so to do this, I'm going to say, come on, I don't know, video equals video model and then inside here, we just need to define all the fields, like this what we're going to say ID is equal to video underscore ID name is equal we're going to need those arguments I'm going to say args is equal to believe it was video put arguments dot parse arguments so we're going to say name is equal to arguments and inside here we're going to put ID or not the ID name and then it's after that, we're going to save using equal arguments views and then we're going to say after views, I think it was like, equal arguments, like, okay, so this is a dictionary remember arguments it stores all the values ​​that we pass in we've seen this many times so I can access them individually that way and well I can do this and that will create a new video model now if I really want to make sure for that to go into the database, so Actually, I'm essentially committing it, what I'm going to do is say DB dot session dot add video, this will add this object to the current database session and then what I can do i.e.
DB dot session dot commit. and what this will do is commit any kind of changes that I made in the session and make them permanent in the database, so now when I say add, I'm temporarily adding this video to the database when I say come. I'm putting it permanently, so what I can do is return that object again, so let's say return the video like this with a 201, but I need to make sure that I add this marshal so that it gets serialized so that Marshall with resource fields again is because this is an object, I can't just return an object, I need to convert something that is serializable and well, this Marshall will serialize this response and make sure that it can actually return it okay, now remove the same thing here, we're going to have to actually do something different to delete.
I'll do it later, but let's see if this works. I think this query might be a little off, but anyway, yeah, let's deal with that, so let's go try, get rid of this delete and see if the put actually works and then we can, yeah, try to get something too , okay, so let's try it now, we're not a hundred percent sure, but we'll try, okay, so let's run this here and do the Python test. op pi and that really seemed to work, so we see that these three happened, it actually returned us the correct information. We can see that that ER serialization is working.
If I press Enter here, then we have a problem, so we get an unexpected keyword argument ID. Well, we had a little bit of a problem here in this query because this should actually be filtered for my apologies, so filtering by video id equals video id, but actually it's going to be id equals video id and then the point first, So what this says, I'm sorry, right? We're going to filter all the videos we have by ID, we're going to look for the one with the video ID ID and then we're going to return the first response in that filter, the first entry filtered by that, the reason we do this is because technically it could filter, Let's say, by views.
I can say that I get filtered by equal views and I could buy anything that has ten views and well there may be several videos that have ten views so I can get just the first one or I can get them all I think, knitting everything so let's do point first and let's see how this works now and scope Python and what is the error here, wait value line one column one graph zero I think something happened here, let me have a quick look, so you can see what actually happened, was that inside our test script here we try to add things with id zero one two three now since those ids already exist in database we get integrity error here it says unique constraint failed id and our server is crashing here.
Now the way we can avoid something like that again is by simply making sure that the id does not exist, so what I can say is that we can check by querying the database or we can do the same. a try-catch to see if this worked or failed, but let's go ahead and say that after the arguments we will set the result equal to the video model, the points filter by ID is equal to the video ID, point first is fine , so I did some testing on my own here to make sure it wasn't leading us in the wrong direction.
What I'm going to do inside here, this may not be the best way to do it, but it will work for our purposes. I'm going to do a query and just check if there are any videos that have an ID that is the same as the ID of the video we want to add. If they do what I'm going to do is abort, so I'm just going to say if the results are like the result exists. What I'm going to do is say abort on abort with a 409 status code, which means this already exists. I'm going to say that the message is equal to the ID of the video taken dot dot dot so this way we won't crash the program.
What we do is we'll just send this cancellation message that says "Hey, we already have this video ID, you can't use that right, so let's try it and see what we get here if we try it, so let's go and try this." Again, okay, so let's do the Python test, stop, hello, and notice that we get a message. ID of video taken. ID of video taken. handle this and just do a query and check if this video exists and if it exists we can just cancel now the same here and analyze it. I want to make sure that we actually get a valid result before we go ahead and return it. so we're going to say if there are no results, essentially if we don't get any results for the id, then what we're going to do is we're just going to abort, we're going to abort with a 404 and we're just going to send the message equal to could not be found. video with that perfect id, that's all we need and let's go ahead and run this now after changing the test script and trying to get a video that has the idea, let's say six, so let's run this.
I'll go back to my command prompt and video. ID taken video ID taken message couldn't find the video with that ID, so that's it when it comes to saving stuff in a database and then handling some of these edge cases like, oh, the video already exists, oh , we can't find it. video identification and so on, now the next thing we could do is do an update. I'm going to leave this as something you guys can figure out on your own because I think with this knowledge you should be able to do it, but I can define, sorry, what's called a patch, so a patch is essentially a way to update, so which is just that HTTP method for the update.
I think update is one too, there's a bunch of different HTTP methods or something, I think methods you can use. but we're just a patch, it's kind of a standard when it comes to updating something and what you could do is the same thing so you can get all the arguments that you want to use to update a specific video and you can change it. this video put arguments like something that has no required arguments, so let's say in an update, maybe they can pass it just the video ID, so if you use the video ID like that and then any other arguments that they want to update the video with , maybe they just want to update the views properly, in that case it would be valid for them to just send you the updated views instead of sending you all the other stuff they want, all the other stuff they're not even going to update properly, so just send you views, so what you could do is query the database, you could get this object, you can modify this object, you can add it back and you can commit and now that I say you know, let's go ahead and do this. because why not, I'm going to make another argument parser here.
I'm going to say video update arguments, dumbasses. I'm going to say a parse point request parser. Let's say video update arguments like this. Oops, video, no point. Video update arguments. dot add argument inside here we're going to add actually all the same arguments so I can literally copy them and I'll just rename it so the video update refresh and refresh and then here insteadif it's required I'll just make all of these optional, this way now the user can send us whatever arguments they want, any of these three or all of these three and depending on what they send we'll update the video with them, so this will be kinda interesting, there's probably a better one. way to do this than the one I'm about to try, but I haven't done this before so I'm going crazy.
I'm going to say args equals video underscore put underscore argh stop parse arguments we are First of all, I'm going to make sure that this video exists, so let's say the results are equal to the video. The video model that queries the filter by ID Video ID will do the same thing here, so if the result and actually is, if the result will say, if there are no results, it will cancel. with a 404 and we're going to say message video doesn't exist can't be updated perfect that's all we need and then what we're going to do down here is if we have a result we're going to update that result so we're going to say for argh in arguments and it's going to be interesting to do that because I just need to check them manually.
I'm trying to think of a better way to do this than what I'm going to do, but we'll have to see here, okay? So if this is going to be a weird way, but we're just going to say if the name is in the arguments, then what we're going to do is we're going to say that the video model point name is equal to the arguments name. Now I think you guys are getting the point that I will literally do this all the time. I will say that if the views are in arguments, then we can say that the video model views are equal to the argument views.
This is probably a much better way to do this. I actually think of one of the off the top of my head, but okay, we only have three things here and we'll say if likes in arguments, then we'll say video model dot likes equals args likes, so essentially we're going to make it so we can update everything here now. I'm doing it since we updated this video model and why am I putting the video model? Sorry this should be the result guys my apologies for that or anything say results and results the reason I am doing results is because I want to change this instance.
I don't want to just change the model itself to result in that name use result results dot like and then what we're going to do is we're going to say DB dot session dot add results and we're going to say DB dot session dot confirm like that and then we're going to put in our square brackets and then we're going to return just the updated object so we'll return a result like that and we could return it with a status but I don't know what the status of updated is so I'm just going to leave that for now in the patch we'll have to remember to add Marshall with Marshall with those resource fields and this should be good, so let me test this and make sure it works and then we'll be fine. go here so instead of get let's do an update so we already know we have these three added so we have ID zero one two let's try to do an update here and see if we can get this to work so please reply the knit patch. so we're going to say base plus video two and here for our data we're just going to pass views equal to ninety nine it's not okay in ninety nine sorry and we'll see when we get our response if this actually worked correctly or not, so let's run, run, we will run the test op.
The name of the video PI message is required, okay, interesting, so let me run it one more time. A video name is required. I think I'm using the wrong argument here, so video argument set. I'm going to say the video update is my problem with that guys let's go back and run this and what's the problem let's take a quick look okay so I'm back. I did a little test there and some things were going wrong so I just figured out those areas I want to go back and talk to. guys, what they were like before we had DB dot session dot add result first of all we don't need to do that anymore because I realized I was just looking at documentation that once it's already in the database we don't need it. to add it back, we can commit any changes we make to the object, but essentially the main problem I have here is that we have this correct result object and I say if name in args if you and args if likes and args then go to the result that , like C, was args, the use result is equal to arc views etc, and we are updating the object that way, which actually works, but the problem is that the name, views and likes actually they are always in this argument, even if they were not passed, that's because what this request parser does here is it will actually automatically fill them with the value none if they are not passed, so what we need to do is to do is, first of all, make sure that if we're going to update that those values ​​are not boogers, so we'll just change these if statements that say if the name in args and arg is a name, not any, so we can write if args a name and what that will do is tell us if this is if this key is not a none value and we don't have to worry about this giving us a key error because we know that we will always have arguments with the name of args views and arguments like we know, they will always be in that dictionary based on the way the request parser works, so I'm going to change this here to say this now and we'll notice that hopefully it should work when we go ahead and change this or when we run this now, so we're just doing I'm sure these values ​​are not none, if they're not none will update the result, we'll commit those changes and that should be fine, so let's go here.
It looks like the server updates automatically and now if I run python tests on top we can. see ID two named Tim views 99 likes 35 and if I go here and now I add say like you know 101 let's see if that updates it so let's run the test again and here we go so you have views 99 likes 101 and just to test I tell him this will work even if I don't add anything. Oh, with zero data there versus zero data with no data and run this and it will stay the same as before, this is how we use a database which is how we update information, this is how we have the correct request parsers and everything else I think that you would really need to do if you are creating any kind of API, especially in flask, so I think that's what I'll end the video here, so this video is taking me a long time to create quite a few errors and things had to go through some ad code in advance you appreciate this effort, all I ask is that you leave a like on the video, subscribe to the channel. and maybe even leave a comment and let me know that it really keeps me going and motivates me to keep making videos.
That being said, if you liked it like I said, please like the video, subscribe and I'll see you in another YouTube video.

If you have any copyright issue, please Contact