Building A RESTful API with full CRUD using FastAPI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
all right i think we're live so sorry everybody i was literally just finishing up writing the article for this post and yeah i completely lost track of time i just uh got off vacation my voice is a little bit sore right now we're kind of losing my voice so if this stream sounds funny sorry about that but yeah i really wanted to stream today got in late last night and we are ready to go so let me share my screen right now and we'll just get things started all right i need to make sure i'm sharing the right screen and uh let me try to zoom in here so everyone can see everything so set this to 150 let me know if the screen size is too small let me know if you can hear me i'm watching the chat uh last stream we actually had some issues with the audio apparently the audio was coming from the mic and not this microphone or from the camera not the microphone so let me know if it sounds bad and uh we'll just get going but before i start watching the comments and seeing the response making sure the audio is good quick context here i went on vacation this last week and i was actually at lake shasta northern california and like always on vacation i get really bored and i decided to take a look at fast api because a lot of people ask me about it i usually don't spend too much time looking into new tech but i did spend some time doing some research built out a crud application i wanted to learn more about it so that's what i did wrote up an article and now i want to stream and make a little crash course on this and yeah just um see what comes up with this or see what we come up with here what uh what we finally produce here and then eventually maybe make some more tutorials on this and a full course okay so audio is good again sorry about my voice i'm trying to drink water here but let's go ahead and check this out so down in the video description i have this link to this article on medium right here so i literally just wrote this up on the plane ride home yesterday from washington to las vegas and i put this together so we're going to have the link to the source code that will be added at the end of the tutorial and here's going to be the structure so first i'm going to take a look at fast api versus django i want to make a comparison uh then we'll go into the installation of fast api we're going to create our first application our first route and then we're going to look into the swagger ui docs if you don't know what that is you'll see in a minute and we'll go into adding path parameters and then we'll go ahead and go into using post put and delete your request and then after that we're actually going to be working with a fake database we're just going to use like a dictionary just a python object um after we go through all the put post and delete requests we're going to add in database models and then we're actually going to start working with those database models so we're simply just going to build out an api there's not going to be a front end and we're just going to get working with this so everyone's saying audio is okay awesome all right so yeah i'm shucking up today i woke up with about four hours of sleep and i just wanted to crank this article out and finish it but yeah look through this anything that i don't know or anything that i maybe uh don't say correctly i'll try to add to the article leave that in the comment section and i will update this um the article probably does have a bunch of spelling mistakes i did not look through it i just wrote it up and sent it out published it on medium so this will be fixed so if i don't know something that well or i don't explain it we'll just go ahead and fix this later okay so this is going to be the guide i wrote this kind of for myself here because again i just learned fast api i can't just learn and teach something without at least having a guide like this if it's django obviously i can just go with it because i know it like the back of my hand but fast api is new to me all right so let's go ahead and get started and i guess before we get started i want to give a big thank you to agora that is the company that i work at i'm a software developer there and agora actually allows me to do stuff like this so i obviously still can make money from my courses from my youtube channel but i am technically on agora's time right now and agora provides an awesome sdk for audio and video integration that's an awesome platform that they have i love to use it and i just want to give them a shout out since i'm technically on their time right now and they are endorsing this right here so all right let's go ahead and get started let's see just kind of watching the chat audio's good looks like everyone's ready to go and i'm sure not everyone will stick through the stream but it's going to be posted after so it will be a full video if it goes great and if there's no major issues otherwise i'll just remake it okay so i'm gonna be using this guide i recommend you use it too but with this i'm just gonna go ahead and follow along so uh first of all let's start with the comparison to django so it's too early for me to tell which one's better or what i like better one thing i'll say right up front here is i personally still am going to use django as my go-to just because i'm used to it but i also think it's a a much better tool if i'm building out a full-scale application specifically i love the fact that django gives me everything that i need in one place it structures my applications and it gives me things like authentication password reset all this functionality all in one place now with that being said one of the things that i noticed about fast api that i really like is its support for async and i love the fact that it's built for building out apis which means that i'm not having to serialize my data every single time i'm trying to render out some kind of model or dictionary i just render it out and it's already serialized because fast api is already built for that fast api is a more lightweight framework so it means that you're going to have to construct all of the things yourself piece it all together so that's kind of what i like about django is that usually it's set up for me and it's easier to get started but other than that i'm not going to really make a comparison after a week of studying fast api and only doing it just in my free time i can't really make a decision here but i'm just going to let you decide that for yourself once we start using it and then maybe in a couple months once i'm comfortable with it i'll actually do a breakdown okay so the first thing to do with fast api to get started is we're just going to go ahead and install it so i'm going to open up my command prompt here i'm going to be using i'm going to be using windows here so we'll just open this up and i won't create a virtual environment if you want to do that go ahead and do it but i'm going to cd into my desktop here and we're just going to run pip install fast api so that's all we need to install fast api we run that installation and then any other installations we need we'll just add to it so fast api is installed i'll close this out and i'm actually going to use the terminal from vs code so let's go ahead and create a new folder and we're going to start from scratch here so we're going to create a new folder and i'm going to call this my api so i'm going to follow the guide that i created in the guide this is how we're going to call our project so let's go ahead and do that and then what i'm going to do is go ahead and just open this up in vs code so i'm going to need to drag everything into the screen on my right here and let's go ahead and just open up this new project here so fast api we have an empty folder and that's it so fast api is very lightweight so it's going to look a little bit like flask in the beginning it's not like django where you get all this boilerplate code so the first thing we're going to want to do is go ahead and create a file called dot py and this is going to be that main file that gets everything started with our application so we're just going to go ahead and create this file and let me just prep my article here let me move this over so i can actually see it okay so sorry one second okay so we're gonna create our main.py file and from here we're just gonna go ahead and configure our application so we're gonna import fast api so from fast api import and then the fast api class what did i do here i remove that so fast api like that okay so we make our import and then once we do that we set up our app here so this is the this is the core configuration to our app here so whatever you call this variable this is what we're going to start using so we'll call this app and then we're going to use a fast api class and that's how we initiate our application now to create our first route you're going to see how easy this is all we're going to do is use a decorator and we're going to use app.get so this is going to be the request method so we have app right here so we're specifying the method and then we're going to specify the route and then once we do that we just create the function that's going to respond to this route here so we're going to call this get items and this route is simply going to return back a list of items so this is going to be like a to-do list or an items list it doesn't really matter uh the first thing we're going to do though is respond with a list of items and then we'll actually get a single item and then work with crud operations with that okay so we have our route we have our function here and we're just going to return back a list so at this point let's just go ahead and add in a list like that so we'll just do item one and we'll do item two and three so just return back some items here all right so main.py file we have that here we have our function and now to start up our server what we're going to do is we're going to need to install something called uv corn and this is going to be our async server so let's go ahead and just move this over and we're going to run a pip install and i'm a little bit too zoomed in so let me actually zoom out here and move this over and we're just going to run pip whoops here's this pip install uv corn okay so we're going to run this installation and now to start up our server we're just going to go ahead and go into uv corn then we'll go into our main dot py file so whatever you call this file right here go ahead and specify that and then we're going to go ahead and start up our app right here so we're gonna do main colon app and then we'll just do dash dash reload now reload is gonna basically it's kind of a little bit like live server where it refreshes our application every time we make a change you don't wanna use this in production but in testing this is a great tool to use okay so let me um make sure i'm doing this right so uv corn main app and reload of course during live streams this stuff happens all the time i might need to change this right here okay let's see of course we're gonna run into our first issue right away but um did i install uv corn let's try this one more time pip install uv cord clear it and then we'll just do uv corn all right first issue let's go let's try to figure this out let's try running this from the command prompt main and then app dash dash reload uv cord is not recognized okay so i must have not installed it let's try that one more time this is where uh the chat can help if you guys know what's going on here okay let's see no issues until the stream it cracks me up all right let me do that let me i'm going to try to run this from my command prompt let's just see what happens here so yeah we'll just use the command prompt so cd into desktop and my api what i call this file okay i'm gonna need a second here so my api yeah i called it that that's on my desktop something that should have took a second now it doesn't work alright so uv cord all right not the path i mean i'm looks like i'm in the path that this is too funny all right i'm gonna need a second here right praveen you're you're a python guy what the heck am i running into here let's see uh praveen is in the chat so check the path yeah i mean all right let's uh let's just try this again let's go ahead and set up our virtual environment maybe that's going to help us so let's just do virtual env and we'll just set up the environment we'll just install everything here all right pip install fast api we'll need to reinstall that since this is inside of our virtual environment tip install all right there we go yeah all right so we got past that wait took way longer than needed to but here we go we started our server with that command that was uv corn and then we specified main app and then we just did dash dash reload okay so this is going to open up our application or turn on our server on port 8000 so i already have this bookmarked here but if you want to open up a tab here go ahead and go to poor 8000 right here and this is the response that we get so took a little bit longer than we thought but yeah this is our first route and it's very easy to set that up as you look at the code here you can you can see that there's not much to it we just have about what five lines of code and that's it so that's our first route and we are ready to move on to the next step so with this uh fast api works with swagger ui it gives us basically this ui for our docs so right now if i open up my my route here at any point if i just go ahead and do forward slash docs with a pound symbol or a hashtag whatever you want to call that this is the the docs that we're going to get so essentially every single route that we add we're gonna get the route right here and we have a way to actually interact with this route here so this is gonna be very useful when we're sending post put and delete requests we're not having to use something like postman we can actually interact with our docs right here and get back information so if i want to test that first route we open up this path right here and we can just go ahead and click on try it out and right here we can click execute and here is that response so we see all the items we see information about our route everything that occurred here and that's essentially just going to give us a bunch of information so fast api comes with uh swagger ui built in with this already and we get this awesome interface so we're going to use this quite a bit here so with that let's go ahead and move on to the next step and we're going to talk about path parameters here so before we actually start working with path parameters and getting back a single object what i'm going to do here is create a fake database so we're just going to go ahead and create a fake database as an object here and then later on we're actually going to create a real one so let's just go ahead and do fake database and this is going to be an object here and inside of this object we're going to specify an id for each object and then we're just going to go ahead and specify the task and at this point we're just going to have an item called task or an item with an attribute of task and then we'll just specify some values here so we'll do clean car and then let's just go ahead and duplicate this and we'll just make three items we'll set this to the id of two and this value has to be unique otherwise we're gonna have conflicting errors so we'll just go ahead and do write blog and then we'll do start stream all right so now at this point what i can do is go ahead and return back this fake database paste that in and let's take a look let's just make sure it's working so we're just going to keep using the docs here so remember we have our port and then docs pound symbol and then forward slash right there well i guess the forward slash will be added by default so if i refresh that and then we want to test this again let's go ahead and click try it out we'll click execute and here we go we see all of our tasks right here inside of this object and then we see each item okay so yeah i see someone asking about the stream will i save it absolutely this stream will be live after and i see someone talking about coding coding is easy yep within the first couple of minutes i'm already running into an error and it's kind of a stupid error but it happens okay so let's give back a single item now so let's go ahead and create another route so we're just going to go ahead and do app.get so the request method is going to be get because we are retrieving some information and then we want to go ahead and throw in a path parameter and for this we're just going to use the curly braces specify the parameter name at this point i can call this whatever i want i'm just going to call it id so this in this case we're just going to get this id value here now in the function let's go ahead and actually pass this value into the function let's go ahead and call this get item so instead of get items it's going to be get item it's not plural and for this we need to go ahead and pass in the id value and i'm just going to specify the type of or the data type that this id needs to be so i'm just going to do colon and i'm going to say this needs to be an integer so if we don't get an integer here this is going to throw an error so we just want to go ahead and throw that in and now we are expecting an id passed in here and that's going to be in the path now to get the actual item let's go ahead and just do return and we're just going to go into our fake database and we're just going to go ahead and get the id value so we'll just go ahead and throw that id so it's either going to be one two or three if we go outside of that limit it's not gonna give us back an item and this is how we can use a path parameter to get a single item so if i go back into my swagger ui docs here go ahead and refresh this again now i'm going to see two paths where i should okay so when i refresh this now i see a second path i see get item i see the fact that there's an id there so if i want to try this out we can actually see that parameter listed out here so if i click try out we need to pass in an id so let's get the first item so we'll click one we're passing one execute and here we have our first item so we have clean car and if i go to the second item we can do two execute and now we're getting right blog and then we can go to three and so on so that's how we can work with path parameters and actually pass in dynamic values so this can be something like a post or maybe a user profile where you pass in that user id and you get back a single item okay so let's go ahead and start working with post put and delete request so the first thing i'm going to do and i keep looking at the article here so i'm actually following this again for anybody that doesn't know this is linked up in the video description so we're moving on to post put and delete request here so the first thing we're going to do is we're going to send a post request so you're going to notice that let me try to zoom in here so you're going to notice that we're going to use app.post instead of app.put and we're also going to send the user to the same url path as the get items route so essentially we're sending the user to the same path but depending on what the request method is whether it's a post or put we're going to change which view or which route actually responds to this so if we see a post request we're actually going to trigger this function if we see a get request we're going to get all the items so let's go ahead and actually build this out so i'm going to move this over here and let's go back into our code all right and i just clicked on slack so that's probably going to open up in a second she's going to close that out that's in my other screen okay so we'll go ahead and do app.post now so we're sending a post request the url pattern is the same as get items and now we're handling a post request and we're just going to do add item okay so at this point we have a few different ways we can go about doing this and what i want to do here is show you uh three different methods maybe there's more but i'm gonna show you three different ways of how we can actually send data through the request body and actually process it and at any point if you see my face covering the code here let me know i'm gonna try to pay attention to that but i'm gonna always make sure that you can see this so i might miss it to just go ahead and say something in the chat make sure i notice it okay so i just gotta alert that or a message from praveen that my code was overlapping it okay so i'll just try to make sure that that's not happening anymore okay so to add an item what we're gonna do here is we're gonna pass in the value that we want from the request body so we're gonna say we want a task and this value needs to be a string so specifically this value right here is a string so i'm going to say that from the request body we are trying to get the task and we want that sent as a string so we're only sending one parameter at this point so let's go ahead and return this and we are going to add this to our database so we're just going to return back a fake database and to actually add this item what i'm going to do here is go ahead and create a new id first and i'm just going to go ahead and go through this object right here so obviously after i refresh any items we add to this database are going to be removed so it's going to be temporary so at this point we're just looking in that dictionary and we're going to go ahead and go into fake databases dot keys and we just want to count the amount of keys so right now there's three so that means the next item that we have here will be four or five and then it'll just keep incrementing that way so we're creating a new id here and we're going to say go ahead and give us all the keys or give us the count and then go ahead and add in a new value so we're creating an id and then we're going into fake databases we'll throw in the new id value and then we'll just go ahead and set that new object here so we're going to set task and then that's going to be the actual string value sent from the front end okay so let's go ahead and check this out so if i go back into the docs ui we'll open this up if i refresh this again we'll just remove that url now we're gonna see another path here try to refresh that okay so now we see add item we see that it's gonna take a post request if i click here and if i look here now i see another parameter that i can actually pass in here so i'll go ahead and click on try it out and let's just say new item added during i can spell during stream okay so that's a that's a parameter that we're going to send via post request so we're just going to go ahead and execute this and down here we should get back a list of all of our tasks or items and this item should be added so we'll click execute if everything went well here we go now we see item one two three and four this is the new item added to that fake database that we have so that object okay so that's a post request now i want to show you another way another way we can go about doing this okay so we have something called pidentic and i'm going to try to give you my explanation of pedantic so pydantic basically allows us to design schema for data that we're sending so it's like a data validation tool that we can actually use here so essentially here's the problem that we can run into right now we're only adding a task but imagine if we're adding something like let's say i'm trying to think of a name or a kind of value but let's just say we want to throw in something like creative so we want to know when this item was created then we'd have to do a string right here um we want to know some kind of rank to this task like a priority rank would have to throw in an integer and so on so if we're passing in all these parameters this can get very messy so this method doesn't really work well if we're sending a lot of data so what we're going to do here is we're going to use pydantic to create a class that's going to create our data structure and it's going to handle all the validation and all the information that we need and then we're just going to throw in that class in here so we're still on that post request so this is the second option i'm going to show you three in total of how we can actually get this data so for this let's go ahead and create a new file and we're going to call this schemas dot py so in schemas py let's go ahead and from pydantic we're going to import base model okay so pedantic i i'm not sure if i need to run an import in the documentation or in that article i wrote that we have to import this but we'll just see right now and if we don't i'll update the article so we're just going to go ahead and create a class here and this will be our item and this is going to inherit from base model and inside of the class we're just going to go ahead and say that we're going to have an attribute of task and this value needs to be a string okay so let's see if we have any errors so far no so i don't think we need to import this it might be already with fast api by default so once we have this we're just going to go ahead and go back into main.py again the class right now is minimalistic but once we start adding a bunch of values that's where you're really going to need this so inside of main.py i'm just going to go ahead and import schemas so we want to make sure we have access to that so we import schemas and this desk that i have does not work well so i keep messing up things that i'm clicking on my keyboard because i have very little space so we imported that we created the class and now we can go down into add item and let's just remove this so this is what we just had at this point so we have our task and then the value and instead what i want to do here is go ahead and throw in the item object and we're just going to go ahead and tell the route here that we're going into schemas dot item so we have a lowercase item and a uppercase item here so that's from this class here so now the data structure has to represent what we have in here so it's going to look a little bit different in that post request so now what we're going to do here is go ahead and still create a new id but for this task we're going into item.task so we're actually going into this class right here and we're getting that task value so if i go ahead and look at my swagger ui docs here let's just open this up we'll refresh it again all right let's go ahead and just click refresh we'll go back into post i want to make sure it's all saved so it's all working and let's just go ahead and send that okay so with that our schema looks a little bit different right here so now we see this object so when i click try it out we're going to see this object and right now it's telling us that we need to send a task so let's say i wanted to require another parameter let's just go ahead and actually test this uh we'll just say um rating let's just do that let's just say we're creating some kind of object that has a rating system so we'll do rating and then we're going to say this is an integer so if i go ahead and go back in here and refresh this we should see that as a required parameter so let's try it out and here we see rating so it's replicating that data structure so swagger ui someone's asking is that swagger api yeah swagger is already built into it i'm trying to remember the best explanation i might add that into the documentation or into the article but fast api already comes with with swagger built into it so it's using swagger okay so let's go ahead and remove that and let's test this so i just i'm trying not to ramble too much here so we'll refresh it let's make sure this works so we're going to click try it out and we'll just go here and we'll just say added using pi damping and let's go ahead and execute it here we go added using pedantic perfect so it's all working okay so some of you may not know your data structure right away or maybe you just want to access the request body and just access the data and parse that data as you please i like doing that with django where when i send data i just go ahead and access that request body and then i get whatever item i need so let's go ahead and actually use that method next so what i'm actually going to do here is i'm just going to copy and paste this and i'm going to comment out this option right here and let's actually paste it in one more time comment this out and i just want to go ahead and leave you both items or both values in the source code so we'll do task and then string and then for this right here we'll just do task so we have option one i'll just comment that right here and then we'll do option two then for option three we're just going to go ahead and access the request body so option number three okay now for this we're going to have to import the body class so this is going to give us access to the request body and we're going to go ahead and change this up right here so down here what we need to do is go ahead and change up the actual schema here so give me a second i'm looking at my notes let's see how was i planning to do this give me a second here i actually don't remember i just studied this over the weekend i'm trying to figure this out okay so here we go so we're just going to do body and this is going to be equal to the body class like that so that's going to give us access to it and then let's just go ahead and change this value so we're just going to go into body and then that should give us a dictionary so we can just access the task like that okay so i think that's it that gives us access to the request body so let's test it from the front end all right let's go back here okay so there's a few issues with this method um right now if i'm using pedantic we're just gonna see that it's taking in a string value so now it's up to us to decide that data structure so if i click try it out we see the string i'm gonna have to manually create this request here so we're just going to do task and then we're going to throw in new item using request body method okay so this should work make sure you're using double quotes here because when this is being parsed in the back end this needs to be in double quotes and not single quotes so let's go ahead and test it we'll execute it and there we go so it worked okay so let's recap our post methods it took a little bit longer than i would like to in a normal tutorial but i wanted to show you all three options so in option one we just go ahead and pass in the parameter that we need set the value and then throw in that value option number two we just go ahead and use pedantic create the database or create the schema and use that item to specify the schema here and then we just add the item by accessing that value from that request body and then here we manually created that request body so what i'm going to do here is by default leave it option number two i think the best route or the best way about going or the best way about doing this is to use option number two so i'll just leave that here and let's go ahead and move on to put requests so a little recap uh post requests are usually meant for adding data to a database put requests are usually meant for updating and modifying data in a database and then delete requests are usually well for deleting data so let's go ahead and go to the next section so we'll just do app.put so we're specifying the request method and at this point the route needs to be forward slash and then we're just going to go ahead and throw in an id so it's the same route as get item here we're just passing in the id as a path parameter and then we're just gonna go ahead and call this update item okay so give me a second here let me just refresh my memory so we're gonna go ahead and call update item we're gonna pass in the id this needs to be an integer so we first need to grab the item that we want and then we're just gonna go ahead and grab the request body so the data that's being sent over we're gonna get item we're going into schemas dot item so that's the data that we're gonna send over and then let's go ahead and return back our fake database okay so we want to update this item so we're going into fake database and then we're going to pass in the id and we're just going to modify the specific task here so we're going into task i'm not covering up the code here no we're good okay so we're throwing in the task itself and we're just gonna say that the task is gonna be item dot task here so that's all we're doing we're going to the same route now this function right here will handle all put requests we're getting the id we're getting the value from the front end and we're updating it and we're returning that database so if i go back to my docs here refresh it we should see this new path here okay so i should see a put request okay so it took a second here we have update items so notice that the path is the same so now it's going to require an id and a request body so if i go ahead and click try it out we see the id so let's say i want to update the first item so we're going into the first item and then for the task here we're just saying updated our first item and let's go ahead and send it all right so we see our first item it's updated here write blog start stream so all our other items so if i want to update another item we're just going to go to two so item two right now is right blog so we're just gonna update this right here so we'll just say write blog updated all right and it's misspell here it's updated and let's go ahead and send that put request right blog updated perfect so that's our put request okay so now let's move on to deleting data so for this we're going to send a delete request and it's going to be a little bit like our update item here so at this point we're just going to go ahead and copy our app.put request we're going to change this to delete we still need the same path here so we have three paths that are the same this one will handle all delete request so we're going to change this to delete item we're sending an integer now we don't need to send any data here with it so i'm just going to go ahead and remove this right here so at this point we're just going to go ahead and delete this specific item so i don't need this we're just going to do del that's going to delete this specific key from this fake database so from this dictionary so we're just going to delete it and then we're returning back our fake database so now let's test this out we'll go back into the front end here let's refresh it it always takes a minute and while it's reloading let me just check the chat here all right cool cool 116 people in the stream awesome okay and just uh for the record this will be posted after okay so now we have our delete request so we have our delete request all we need to do is specify the item that we want to delete so let's delete the first item we'll just go ahead and click or add in one for the id we'll execute it and here we go so now we only have two items in our database if i want to delete the second item we'll just add in two execute and there we go now we have one item in our database so if i go to get items try it execute it that's all we have awesome delete is working all right so up until now we've had we've been working with a fake database now it's time to create a real database so for the or orm we're going to be using sql alchemy with fast api you can use whatever database you want um we're going to be working with relational databases so we'll use sqlite typically i would use something like postgres but if you want to use something like mongodb i don't see any reason why you couldn't use it but we're going to focus on sqlite this can work with any database here so let's go ahead and start building this out so we're going to go ahead and go into our application again now and we need to start setting this up so the database part i'm going to be honest with you this is the part that i was literally writing up the article right before the stream that's actually why i started it 15 minutes late so there's going to be certain things that i might not fully understand i know how to make it work but i might not give you the best explanation so if i don't give you the best explanation go into the article after the stream and i'll try to update uh certain definitions and things that we're doing so this specific article right here go ahead and look at this after the stream i'm going to try to update it again if you have something in the comment section that you want to say let me know in the comment section and then we'll actually modify this so in this article we are on database and models so we're in that section the first thing we're going to do is install sql alchemy that's our orm to work with our database then we're going to create a database.py file this is how we're going to configure our database once we create it we're going to write some code here and then we're going to create our model to represent the actual database tables so for those of you that don't really know how models work or how database structures work typically in python you would create a class that would represent a database table so the actual table would be the class the columns in that table would be the attributes in a class and then each individual instance would be the row uh in that table so we're just creating a replica of how that's supposed to look in designing the schema okay so let's go back up here and let's start working with that so we're going to add in a database dot py file and in here i'm going to run some imports and i'll just try to explain as best as i can and what we're importing and why we're doing it what we're using so the first thing is it's going to be from sql oh i forgot i need to run a pip install okay so go ahead and activate my virtual environment install sql alchemy all right so that should be installed and let's go ahead and start those imports so from sql alchemy import so let's see what was this first import so this is going to be create underscore engine so this function is going to create our database engine so this is where we specify where our database is going to be the type of database and where it's going to sit or i already said that so the database type so whether that's sq or sqlite postgres and so on the file path to it and the actual database name so that function will help us create that then we're going to do from sql alchemy dot e x t then dot declarative and then keep spelling declarative ron so from sql alchemy ext declarative let's import declarative underscore base right and the last import we need is going to be from sql alchemy dot orm import session maker okay so we have our imports and the first thing we need is to create our database engine so we'll just do creates database engine so we're gonna go ahead and make a comment first and then actually create it so the engine here is gonna be create engine then we're going to specify the database type so this is going to be sql lite then we're going to do colon forward slash forward slash forward slash and then we're going to do to do dot db so that's going to set the file path for my database and it's going to create a database here once i actually execute this and it's going to be called 2d dot db okay so that's the database engine now the next thing we need to do is go ahead and set or create a base class here and i'll be honest with you i need to do some more research on what base actually is doing or declarative base but at this point let's just go ahead and use a declarative base function i know that this returns a class that gives us ways to access the actual database so we're going to go ahead and add that and then i'll update this in the article later so the next thing i want to do is go ahead and do session vocal so this is how we actually work with our database and have sessions with us so we can access it update items retrieve items and so on so we're going to create the session local class and this will be session maker and we're just going to bind bind the engine then we're going to go ahead and do expire underscore on i'm not blocking the code here so expire on and then we'll just do commit and this is going to be false okay so we made our imports we have our database engine we set up the base class session local using session maker and we are ready to move on to the next step here so once we have that we're going to go ahead and go into our models here and we need to actually define our database tables so we're going to create a new file called models.py and in here we're just going to go ahead and import some things from sql alchemy so from sql alchemy we're going to import column for for our database tables here so column integer for the data type and then we're just going to go ahead and throw in string so we need an integer and a string and sql alchemy just want to make sure the spell right okay so we also need from database we need to import that base class so import base and let's go ahead and actually create the database table now so this is going to be called item we're going to inherit from base after that we're going to go ahead and create our table name so double underscore right here and then we're going to go ahead and call our table name table name double underscore is gonna be items so that's gonna be a string value and then we need an id for the id you can use a uid whatever you want here at this point i'm just going to go ahead and do column and we're just going to make this an integer so we in imported integer so the integer and then we're going to set this to the primary key so this will increment by default so we won't have to do that uh addition for the auto incrementing like we were doing in the front end for that fake database okay so we specified the id then we want a task here so that's going to be a string value so we'll do column and then we're going to do string and then we're going to set the limit here to let's just do 256 characters so that seems to be the standard so for now we'll just leave it like that and that is our database table so we can add a lot more we can create relationships but we're not getting into that right now we just want to know how to create add update and delete items from this database so we created the database we have our model now and now it's time to actually access this database and create it so we still don't have our database here in the file here so what we're going to do is we're going to go into main dot py and we're going to make some imports and actually create that database so first of all we're going to import the pens here from fast api that we want to import let's see import our models so we just created the model so we want to import all of that and then after our models we want to go ahead and import some stuff from our database so from database that's this file right here we want to import let's see i see python engineer in the chat yep it's time for fast api i've done too much django stuff now we're just going to work with fast api for a little bit i just worked with it over the weekend or over this last week and wanted to make a video on it so from database import we're going to import base engine and we're gonna import shoot give me a second so engine session local and then from sql alchemy we're going to import session not used to this keyboard after a week of not using it so sql alchemy dot orm import right so we have our imports now to actually create this database what we're going to do is we're going to access base and then we're going into meta data dot create underscore all and we're going to throw in our database engine so what's going to happen here is if we don't have a database yet this right here will create our database using the engine configuration right here that we have in database.py so it's going to create a database called to do in this file path here if we have it it's not going to create it so on that first initiation it's going to go ahead and set that up for us so if i go ahead and refresh that so i saved it now you see 2do.db so here is our database it's an sqlite database we're not going to work with any plugins to actually see that data it's there though later on if you're using something like postcrest that's where you can see the database tables but right now we're not going to worry about actually seeing anything there so that's what this did it goes ahead and creates that database someone's asking if we're using flask no this is fast api okay so we create the database now the next thing we need to do is get the session so i'll be honest with you i was reading up documentation i didn't spend a lot of time on this next section here but all i understand is that we're going to create a function that's going to allow us to access our database and essentially get the session so we can make requests and actually update things so we're creating a function called get session and i'll update this inside of that article too if you want to know more so we're going to use session local so we're going to specify the session inside of the get session function and then we're going to do try yield says y i l d like that yield and then we're just going to do session and then we're going to go ahead and do finally i want to make sure you can see the code here and this will be let's see session dot close all right so we have a function now to actually get recession shivo's asking can you teach me pi script yeah i'm not into that i don't like the idea of pi script i think it's cool i guess but python in the front end that seems a little bit weird okay so we have our get session function and let's go ahead and actually access our database so to recap created our database and all the configurations created our models made some imports here created the actual database and now it's time to access this so get items right here so let's go ahead and modify this we're just going to go ahead and change this so instead of accessing our fake database we're going to go ahead and get all the items so inside of the get items function we're going to go ahead and get the session here and session will be session and then we're going to do equals depends and we're going to go ahead and call get underscore session so we're going to go ahead and call this function right here so this is going to give us access to the database and then we're going to go ahead and specify the items and this is going to be session.query so now we're working with the sql alchemy orm and this is going to be session.query and we want to query models dot item so that object and we want to query all the items so this is the bdfast api i don't have to serialize this data like i would in django so we got all the items and this should now work okay so let's go ahead and test this out and at this point we shouldn't have any items in the database so let's go ahead and refresh it and we should see an empty python list or i guess json array so let's try it out we'll execute it and here we have nothing so we have this empty list and that's perfect that's exactly what we need so let's go ahead and actually add some items before we work on getting back a single item so we'll go back into our post request now and let's go ahead and just modify this one so we're going into add item and at this point we still have item schemas that looks good so we're just going to go ahead and get this session right here and we're just going to paste this into add item so bring this down here so we get our session here and now what we need to do here is go ahead and remove new id so that's going to be auto generated so we just need to go ahead and create a variable for an item and we're just going to say models dot item and this is going to be equal to task so we're updating this specific attribute so we're updating the task attribute of this item model or this item class and we're going to say the task is equal to item.task so that's from the schema right here using pydantic we're accessing the task value we're going to update it then we're just going to go ahead and add this to the actual database so we're just going to do session dot add and we want to add the new item to the database then we're just going to go ahead and do session dot commit and we'll just do session dot refresh okay so we're gonna refresh it and we're just gonna go ahead and throw in item like that okay so we don't need this anymore i can remove that and let's just go ahead and return back the item okay so let's go ahead and check this out so i'll save all this we're actually adding an item to the database we'll go back to the front end okay so give it a second it'll need to update okay so we have add item try out and we'll just say this is our first item let's go ahead and execute it looks like everything is good we see our first item the id is one now and if i go to get items try it out execute here we have our list now when i refresh this or turn my server on and off now it's not going to remove all the data from our database because we're actually storing this inside of that sqlite database so it's all there now this data will not be removed now we actually have some form of real database even though sqlite is usually not for production but we have data actually stored now so we have our first item let's go ahead and just add in the second item we'll just do this is our second item we'll execute it and we'll just add in that right there so at least we have something or we have a little bit more here so let's execute that and let's see okay so now what i want to do is actually get a particular item so we'll go back into our code here so we added the item i just wanted to skip to that step just to make sure we actually had some data so we'll go into get item now and we're going to do the same thing we're going to we're getting that session so we can access the database and we're going to access this specific item here we'll do item and this is going to be equal to session dot query and we're just going to go ahead and get the model of item and we're going to call get so instead of all we're going to do get and we're going to get back the item by its id value so we're going to go ahead and get this id and that's going to query a specific item so we fix the indentation here save it and let's just return the item okay so that should return back a single item let's check this out okay so we have get item we have two items in the database so let's get the first one try it out we'll get one execute there we go this is our first item and then if i want to get item number two execute and then if i do three i think it's just gonna throw an error yeah so we have an error or i guess it's null there's no item in the database with that id okay so that's how we get an item by its path parameter from the actual database let's move on to updating an item so we're almost done with our crud operations so let's go into update so here we still have the integer we still have the schemas we want to get our session okay so we'll throw that in right there so that's inside of the update item route and i'll zoom out a little bit so you can see that or see all of it and at this point let's remove our fake database and what we're going to do here is just go ahead and item and then modify it so let's see trying to remember how i did this so we have item uh we're going to go ahead and get the item so let's just use the same method right here we're getting the item oh no that's to modify it so let's go back to get items so we're going to specify this and i might need to update the actual article it looks like i have some mistakes there because i'm actually following that right now and that's what's throwing me off so let me just think about this my or think about it clearly by myself without actually referencing the article so we have our item once we get the item we're just going to go ahead and start modifying it so i think we can just do item dot task then we should be able to just do item dot tasks like that from the front end so let's actually call this item object because i think this name right here might actually conflict so we're just going to go ahead and specify that update the task this is going to be from the pedantic schema we're updating the task value and then we're just going to go ahead and do session dot commit so we're going to commit these changes and then we want to return back this item so we'll just return back item object and then we'll just make sure that it's updating the actual database okay so save it refresh it let's check this out see if this is working so we'll go into our put request so we want to update the first item so we'll just do one and then we'll just do first item was updated execute and it looks like we have an error so let's see what's going on here yeah something's not right here so get session oh i see what i did added in two commas there okay so we're going into our put request updating the first item all right execute and here we go first item is updated so if i go back it'll actually let me slow down okay so first item was updated i realized i went really fast here let's go back up to get items let's see how that looks let's try it out execute and here we go first item is updated and we still have our second item so that's how we update an item in the database okay so let's go into deleting items so deleting items is gonna be very easy we're just sending a delete request and then simply removing that item from the database so we're still gonna go ahead and use session right here so we still need to get all this information we only need the id to get the item we're just going to go ahead and access the object right here throw that in right there and then we're just going to do item object and then we're just going to call let's see how we're going to delete this so we'll just call delete so we're actually going to use session so session dot delete and we need to specify the item that we're deleting so item object we're deleting this yeah i definitely need to update the article so if you're following it right now it might be a little bit outdated or messed up so i'll go ahead and fix all of this okay so session.commit let's do two ss there session.commit and then we'll just do session dot close okay and then we'll just say item was deleted right let's go ahead and check this out we're passing in the id refresh it let's go to delete let's delete the first item execute item was deleted so let's go back into get items let's make sure it was actually removed execute and now we only have one item in the list all right so that's it for this code out this crud application so we're not dealing with the front end if you want to use some kind of front end like react vue angular svelt that's all up to you i loved working with this swagger ui docs that we get with fast api um i'll probably end up doing videos or maybe even a full tutorial on comparing django flask fast api and making comparisons to them maybe building out the same api with all three but yeah that's all i wanted to do here show you those code operations we got this done in an hour this video will be posted after so i want to make sure to keep it as short as possible so i'll probably end the stream right here but um with that make sure you reference the article i'm going to update it that's all linked in the video description and this source code that we just worked on will be in that article so make sure you go to the article and then you'll have all the source code right here so i created a placeholder somewhere here so let's see at the very top of the article we have the stream url so that's this stream url we have source code i said it will be added right here so i'll make sure to add that in fact what i'm going to do here is quickly just push this to github and then if you want to uh if you want to ask some questions go ahead and do that i'll try to keep this stream at about an hour and five minutes or an hour and 10 minutes i figured a little bit more time won't hurt it so while i am pushing this to github go ahead and ask some questions interact in the chat but let's go ahead and do that so i'm just going to go ahead and push this so give me a second here i just need to open up my github account and i'll be watching the chat oh i'm really losing my voice it's getting tough to talk okay so give me a second [Music] okay so let's bring in github here and we'll go into my repositories we'll go to new new repos and we're going to call this fast api crud app live stream this is kind of a long repo name but let's go ahead and do that and i won't add a description yet we'll leave it as public i'll maybe update this later if somebody wants to add a readme to it i'd love for you to make that commit for that pr and i will approve it so let's go ahead and create the repo and what i'm going to do here is go to medium right now and i'm going to edit this article and then i need to push the code so we'll go in here source code is now linked up there we go so that's the source code save and publish it so i just updated the article so now you can access this this is all in the video description might take a second to actually update that okay so while that's updating let's go ahead and actually push this to github so we'll just do get knit hit add i'll just uh move my face out of here just in case i'm blocking any code so get add git commit dash m it's about tutorial i actually got to do that i've tried spell one time i just need to sit down and study it write up an article just like i did today and maybe i'll just live stream i really enjoy doing this okay so we made the commit we'll just do git push dash u origin master oh i need to get the get the remote here so go back into github and we'll just add it kind of sucks that we started off with a bug because this stream is going to be posted after and now that's always going to be there okay yep push dash u origin all right so source code should be updated like i said if anybody wants to submit a pr give me a readme file on how to set this up and maybe a description i would love that i'll approve it so that's all inside of this article now if i refresh it the link should be here so here we go we have the source code again this article is in the video description all right so how easy is it to add status codes uh very easy there's a lot of content on this in the fast api documentation yeah when i was looking through it i just didn't go through that right now because we're focusing on crud so yeah adding those status codes are actually pretty easy here let me um stop sharing my screen here and i'll just look through some of the chat here yeah i got to get that swell tutorial uh django react course i actually have one i know that the second react 18 came out it was outdated i mean it's not outdated because it's i mean you don't always have to have the latest code so yeah it sucks because people always want that so that usually means to a lot of people it will be outdated uh the stream is over uh we're just gonna post this after let's see is there a better way to work on simple projects for beginners live i don't know what you mean by live but yeah i'm not exactly sure how what that question means authentication yeah i do need to i do need to uh i want to work with authentication with fast api you'd probably be using uh json web tokens for that so yeah i'll have to do a video on that and maybe use something like react on the front end to actually handle the authentication all right so that's it for this tutorial it's uh at an hour and seven minutes this will be posted after again it sucks that we had the bug in the beginning but hey that's that's life we'll uh we'll see you guys later and again thanks to agora for essentially sort of sponsoring the stream even though it's not actually sponsored but for letting me work on their time with that um i got to get back to work with some other stuff so right see you all later
Info
Channel: Dennis Ivy
Views: 27,736
Rating: undefined out of 5
Keywords:
Id: FOZNYBu8u18
Channel Id: undefined
Length: 67min 41sec (4061 seconds)
Published: Mon May 23 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.