Python FastAPI Tutorial: How to Connect FastAPI to Database

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up everybody and welcome back to coding with roby where we go over all new things code to keep you updated on modern tech in today's video we are going over part two of our fast api tutorial where we will be implementing a database [Music] [Music] all right everybody let's pick up where we left off so we left off by creating a new book class which is part of pidentic for our data validation we have a books list where we are appending to the books list and returning the books list and removing from the books list all based on the crud operations of the restful apis that we're passing in we have an app.git which is our read api which returns all the books on our list post which creates a new book and appends it to the list update a new book that is already in the list and then delete a book that is already in the list and now for this video we are going to be creating a database and connecting all of our crud operations and our fast api application to a database so we no longer have to handle it within a arbitrary list that gets reset every time the application is reset so a database definitely makes sense in this application so the first thing we are going to do is create a database.pi file and this database.pi file is more or less the configuration that we're going to be using to manipulate and create a database and now we're going to be using sql alchemy sql alchemy is the orm or object relational mapping for our database so our sql alchemy is going to be handling all the behind scenes code to be able to manipulate and change our records within our database and sqlite is a requirement for this video so if you do not have sql lite installed on your windows or mac machine feel free to jump over to my video where i walk you through step-by-step installation of sql lite and once you install sqlite come back over and we'll install and set up fast api with your new sqlite installation before we get into that let's create our database.pi file so we can right click on fast api and say new python file and let's name it database and now once we are in here we're gonna have to install sql alchemy and it's a fairly easy install just make sure you go into your terminal in the directory of the project you're in again i'm gonna be using a virtual environment you don't have to be using a virtual environment if you do want to create a virtual environment go check out the first video where we go over virtual environments however here i'm just going to say pip install sql alchemy and just like that we installed sql alchemy into our virtual environment let's now do some imports so the first import we're going to say is from sql alchemy import create engine and from here we're going to create another import so from sqlamy.org import session maker and lastly we're going to say from sql alchemy dot ext dot declarative import declarative base all right now we have all the imports we need for this project and i will zoom this in a little bit so we can see better from here let's say sql alchemy underscore database underscore url is equal to double quotes so a string sqlite colon slash slash dot slash books dot db in this books.db is going to be created automatically by sql alchemy into our application and the sqlite dot slash is just finding location of this books.db file that's going to be getting created automatically all right and now we need to create a new variable engine which is equal to create engine and then as the parameter we're going to say sql alchemy underscore database underscore url which is the variable we just created comma and then we're going to say connect args for connect arguments and this is a sqlite specific argument where we're going to say check same thread of boolean false all right and now we're going to create a new session local and our session local is going to be equal to session maker and we're going to be passing in three parameters auto commit which is equal to false auto flush which is equal to false and bind equals engine and last we're just going to say base so base equals declarative base and make sure base is capitalized this is everything we need for our database.pi file where we are doing all of our connection processes to our sqlite database and just for reference if you do not have sql lite3 installed on your pc whether it's windows or mac go check out my video on how to install sqlite on either one of the operating systems i put it all in one video and then you can jump back to where we are now next let's create a models.pi file and our models.pi file is going to more or less be the table and the columns of our books file that we want to put in the database so let's right click on fast api and create a new python file of models.pi once inside the models.pi file we're going to have to do a couple imports so from sql alchemy we're going to import column integer and string we're also going to import base from database and again i'm just going to make this a little bit bigger so we can see all right and now let's create a new class of books which inherits base and then inside i'm going to say underscore underscore table name underscore underscore and that is a sql alchemy specific thing to be able to name our database table whatever we have after this so after our table name let's say equals books so now our database table is going to be called books and now let's say inside our books table we want to create columns for our records of books that are going to get saved to the database so here i'm going to say id and yeah we're using uuid currently in our books.pi file but we're going to change that to now use ids so id equals column integer comma primary key equals true which primary key is our unique identifier of each record and then index equals true and index just means when we search for this specific column which is id we can get some cash and we really accelerate our search results so since we're searching by id a lot since that's the primary key we're going to say index equals true and then we're also going to want a title column which is equal to column string author which is equal to column string description which is equal to column string and rating which is equal to column of type integer all right so now we have our database.pi file created which has all of the settings and parameters to be able to set up a database instance and now we have our models created which is going to be the table within the database that we are creating now let's go back to our books.pi file where we can manipulate some of the code to now automatically create a database automatically create the books table if it does not already exist and then we can connect all of our crowd operations to now use the database that we're creating so one of the first things we're going to need to do is import our database and sql alchemy things so under uuid let's say import models which is going to import our models.pi file let's also say import engine and session local from database and then let's say from sql alchemy.orm import session and we don't need this comma right here so let's delete that all right and now under app equals fast api let's say models dot dot and we're going to pass in the bind equals engine and here when this gets ran this is going to create the database and table if it does not already exist and now we need to create a new function and this new function is going to be called get db and really what this is going to do is we are going to create a session local instance which is creating our db instance and then we're also going to be closing the instance and now database connection processes are usually a singleton type of protocol so every time we open a database connection we want to make sure we close the database connection so we're going to be creating a function that kind of handles that process by itself so let's start by saying def get db empty parentheses and then we're going to say try db equals session local yield db and then i'm going to say finally db.close okay this is looking really really good so now the first thing we need to do is just start changing some of this code so this id equals uuid we can delete this completely and the reason we can delete that completely is that we're going to be having our database handle all ids and auto increment and handle all of the id management on its own which removes any kind of id management from us which is perfect we don't have to pass in an id at all and now let's scroll down to our read api return books and now this can be the very first thing we manipulate and now we're going to be using a dependency injection platform on fast api so every time this function gets called we want to automatically open up a database session and automatically close that database session so let's go to the very top and in fast api let's add a new import of depends and now within pretty much all of our parameters we're going to be calling our dependency injection so within this parameter we're going to say db of type session equals depends and we're going to be passing in our get db function as the argument and parameter and we're not going to be passing in the parentheses of our get db just get db and this is going to handle all the dependency injection for our database session for application and now instead of returning this list of books we're going to return everything inside the database so let's say db.query and then as the parameters models.books dot all and if we actually ran this application we're not going to get anything back and that's because we don't have any items within our database so before we do this i'm going to manipulate our post our create book to save an item to our database first before we go and test this so right here we say create book we're going to be saying book of type book we're still going to be passing in a book but also we're going to be passing in the dependency injection argument that we did for a read api so comma db of type session equals depends get db okay and let's delete everything so far well we can return the book so let's just keep delete this first where we're saying append book to the list of books and the first thing we're going to do is create a new variable or a new object book underscore model which is equal to models.books and this is going to be mimicking our models.pi so our id title author description and rating but again we only have to handle these four attributes title author description and rating and that's because sql alchemy is going to handle id for us once we create this empty book model we want to pass in all of the data from our book object into this book model object so we want to say book model dot title equals the book title bookmodel.author equals the book author book underscore model.description equals the book description and lastly book underscore model.rating equals the book.rating after we do this we now need to add book model to our db which gets it more or less in the session of the db it actually hasn't done anything yet we're just getting it ready to be committed to our database and we can do this by saying book model and now we need to commit that model so db.commit all right so we've made a lot of code changes we created our database.pi which is all of our settings for sqlite and sql alchemy we created our models which is going to be our table and database for our sqlite we then within our books pi made some adjustments where we're creating a dependency injection platform where we're saying db of getting our session and closing our database and we are now calling our read api in create book from the database let's jump in our terminal and let's type in uvicorn books colon app dash dash reload to see this application in action let's open up our browser refresh and right now if we say read api and we say try it out we're going to get a 200 successful but we're not going to get anything returned and that's because our database is being completely empty if we go to our create book and say try it out we can see that we no longer have to handle any kind of ids or primary keys and now let's type in a title author description and rating so the title is going to be eric's fast api course author eric roby description the fastest way to learn fast api with a rating of 100. let's execute and let's go back to our read api and execute this api and we can see that we get a id of one now and that's because our auto increment for sql light and sql alchemy is working and then we have a book this is pretty cool this is all going to a database so now let's adjust our application for put and our delete to now use the database so our app.put book id is going to be completely okay but other than a uuid we're going to say end our book of type book is ok and here we're going to be passing in our dependency injection of our database again so db colon session equals the pins get db and we can delete just about all of this code and here we're going to say a book model so we're going to be creating a new instance of book model which is going to be equal to our db.query so now we're querying our database and we're going to be querying the table of models.books and we're going to say dot filter which is now us writing sql commands or being able to you know edit our sql statement and then inside our dot filter we're going to say models.book id equals book id and this is going to say look through every record until models.books.id is equal to the book id we're passing in and then say dot first and dot first just means when you find the record in the execution and return that one record because there should only be one record of this instance because we're using the primary key so there's no point in continuing the execution once we already find our record all right so now that we have our book model we want to make sure that this book model is not null or none and that just means once we look through the database if that primary key doesn't exist we don't want to be able to update it because the book doesn't exist so let's do before this raise http exception we're going to say if book model is none then raise the http exception if not let's continue executing this function and you can highlight all this and press tab to be able to move everything to the right and this is actually going to be called a guard clause and a guard clause is just a way of ending a function execution statement due to variables or objects being null and kind of doing null checks throughout the application now the other way you could do this is saying if model is true or is not null then wrap the entire function inside that function statement or that if statement but that's not good practice guard clauses make everything significantly more cleaner when checking if an item is null or none so we're going to be using this guard clause and then we're going to be doing pretty much the same thing we did for our post so book underscore model.title equals book title book underscore model.author equals book author book underscore model dot description equals book description and then book underscore model dot rating equals book rating then we want to add bookmodel to the database and then commit the database and then just so it's a little bit more pleasing i'm going to return the book after we commit the database okay this looks really good now let's redo our application and open up our swagger ui and again since we're using a database if we say try it out and execute our application and data will still be there so now i'm going to hop on over to our post i'm going to create a new book where i'm just going to say title string string string rating is zero try it out execute if we go back up to our get and we execute this we're going to see we now have two books in our database if we go over to our put we want to say update a book we want to update the book with a second id and i'm just going to change the rating to 50 just so we can see it in action and then execute we get a status code of 200 with our book information if we scroll back up and check out the get and execute this we can now see that our book with the id of two now has a rating of 50. woohoo so the put is working and now let's just adjust our delete functionality to now be able to delete a book so to do this i'm going to delete all this code just like we did for the put and we're going to want to pass in a book id of type it now and again we're going to want to pass in our dependency injection of our database so db of type session equals the pins get db all right so for delete we have to operate a little bit more cautiously and what we're going to do now is we're going to first check to see if the record exists so we're going to say book model equals db.query of models.books dot filter models.books.id equals bookid.first to make sure that exists and then i'm going to do the exact same thing for this arrays http exception so if book model is none quick guard clause to exit the execution and just return http exception and now we just want to get the deletion ready so we can do that by saying db.query models.books.filtermodels.books.id is equal to book id but this time we're going to say dot delete and then db.commit all right let's clean this up a little bit all right so i saved the application it's going to refresh our yuvacorn server open this back up and if we start by saying read api try it out execute we're gonna see we have two books id of one and id of two if we scroll down and go to our delete book and we say we wanna delete book two execute we get a null response and that's okay with a status quo of 200 and if we scroll back up we execute our git we can see that our book with the second id has been deleted so in this video we created our database.pi file which is all of our settings of setting up our sqlite database we created our models.pi class which is going to have all the tables and columns of our database for our books table and then we enhanced our books.pi file to now change all the crud operations to now query the database instead of saving it to an arbitrary list and we probably can also delete this uuid from the top since we are now using just normal ids all right and again if you need any help with using sql lite or downloading sqlite onto your machine i have a video for that you can just click the video and it will bring you to that and you can come back to our fast api course now you have it you have a fast api application with all the cred operations that are now connected to a database congratulations and keep learning
Info
Channel: Eric Roby
Views: 32,133
Rating: undefined out of 5
Keywords: python database, fastapi, fastapi database
Id: 34jQRPssM5Q
Channel Id: undefined
Length: 26min 11sec (1571 seconds)
Published: Thu Feb 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.