How to build a FastAPI app with PostgreSQL

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this quick step-by-step tutorial we're going to show you how to set up postgresql with fast API my name is Eric Roby I'm an instructor a software engineer and a cloud Enthusiast so if you want to learn everything Tech come check out my channel and with that let's dive into fast API with postgresql alright so what we're going to do in this project is set up fast API with postgresql and postgresql is one of the most popular databases in the world for relational databases and fast API is an upcoming and super popular python microservice framework so let's dive in and let's create a fast API and postgres application so the very first thing we want to do as always is go ahead and create a virtual environment so let's go ahead and say new terminal and do this let's just go ahead and say python3 Dash m v e and V and then we'll name the environment just EnV for the environment and that will create an environment right here in our directory and now let's go ahead and just activate the environment by saying Source EnV slash bin slash activate all right and we can tell that it's activated because we can see this little environment right before our directory so that's awesome stuff and now let's go ahead and install all the dependencies we need for this application and we can do this by saying pip install we know we need fast API we are going to need SQL Alchemy which is going to be our orm our object relational mapping to our postgres database and we can just type in SQL Alchemy and the very last one we need is some kind of connection Port that'll connect our postgres to our fast API application and we can do this by typing in Psy [Music] c-o-p-g-2 Dash binary and once you type that in it'll just start downloading everything we need for this application in our and virtual environment and a virtual environment is super popular because instead of having all of these dependencies on our computer we can Silo these dependencies into each project so this is our fast Epi postgres directory and we can create an environment for this application without all these dependencies going to all of our other python applications so create a virtual environment and install all these dependencies and now we can go ahead and create our application now for this application we are going to be creating this quiz game this quiz is going to have a quiz and a question and that's pretty much it we're not going to have it fully functional but we're going to be able to save multiple tables to a postgres database so you can kind of see where we're going in that direction so the very first thing I'm going to do is just right click and say new file and we're going to call this main.pi and this is going to be our main fast API file and the first thing that we're going to do here is just say from Fast API we want to import fast API and since we're here we might as well just go ahead and do our HTTP exception and our depends these three things we're going to need in our fast API application so we can run and be able to call the apis and everything now the next thing we want to import is pedantic so we can say from pedantic we want to import base model and this is the base model for all of our data validation that we're going to be using with pedantic we next want to say from typing we want to import list and annotated and let's go ahead and say that's everything for right now as always just like any other fast API application we now need to create our app and we can say app equals fast API and don't forget the parentheses now here let's go ahead and create our two pedantic base models so for choice and question so we can start by saying class Choice base and we're going to pass in our base model and simply inside here we want Choice text to be of type string and then we want is correct to be of type Boolean and now we really want to do the exact same thing for questions so we have our choice base with our base model and now let's go ahead and do our question where we can say class question base and inside here we can pass in our base model where we say question text is of type string and then we can say choices is going to be of type list and we will pass in our choice base so when we call our pedantic Choice base it's going to have a text and is that question correct for the choices of for a multiple choice quiz and then our quiz is going to have a question and it's going to have a list of choices and one of them going to be correct all right so if we continue on we need to then go ahead and start creating our API endpoints but before we do that let's go ahead and create our data models for our postgres database let's go ahead and just create the database for postgres and then let's also create the database.pi file that will kind of connect it all together our fast API application with our postgres database now I'm going to first say new file and then I'm going to create a new models.pi and in this models.pi file we want to really import a lot from SQL Alchemy and again SQL Alchemy is going to be our object relational mapping it's our orm that is going to connect to our database so we can do simple queries to be able to fetch data from the database so we can say from SQL Alchemy import and we want to say Boolean column foreign key integer and string so these are going to be all the different types for our database perfect and now from here let's go ahead and just create our database.pi file real quick because I forgot we're going to need this for our models.pi file so let's go ahead and create our database.pi file and inside here let's say from SQL Alchemy import create engine then we want to say from SQL Alchemy [Music] .orm we want to import our session maker and then lastly let's say from SQL Alchemy dot EXT dot declarative we want to import our declarative base now after we got these done we can now go ahead and create our URL string to our postgres database but before we do that let's go ahead and just open up PG admin now if you don't have postgres or PG admin currently yet installed on your machine I will be creating a video when that video is created you're going to be able to see it around me somewhere feel free to click on that um but for the meantime let's go in here inside our postgres PG admin which is a GUI for postgres we need to First create our database so we can just right click on databases and say create database and inside here I'm going to call this quiz application YT for YouTube and then I'm going to say save here we can see that we have our quiz application YouTube If we go into our schemas and we open up our tables we can see our tables is currently empty so now let's go ahead and go back to our application and from here let's just go ahead and say URL database equals and then right here we want to say postgres ql colon slash slash and now we need to type in the user now my username on my postgres database is postgres so I'm going to type in postgres and then you need to type in a colon and now the password to the user and my password for my user is test1234 exclamation mark and now we need to say the path so we can say at localhost and postgres is always on Port 5432 so we can say of 54.32 and then we can say slash quiz application y t so our URL to our database is going to be our path to our local installation of postgres with our user's first name and last name all right and now from here we want to say our engine so we can create a new engine which is equal to create engine and inside here we'll pass in our URL of database and now we need to create our session local so we can say session local equals our session maker and now inside of here we want to say Auto commit is equal to false auto flush is equal to false and lastly we want to bind our session local to our engine right above and our engine is going to necessarily going to create our engine of our database with our path of our fast API application to our database all right and then the very last thing we want to say is base which we're going to be using in our other files is equal to our declarative base all right now let's go back to our models and we already imported SQL alchemies Boolean column foreign key integer and string and now we want to say from database import base and now we can go ahead and create our tables that we want saved in our database so we know that we want our questions so we can say class questions and we want to pass in base here when you want to name the table something so we can say table name which is underscore underscore table name underscore underscore and here we want to equal this to questions so we're going to name our table questions and we want this to have an ID which is a column in our database table where it's going to be an integer the primary key for this will be true and the index will be true now a primary key means it's going to be like the unique identifier for this entire question that we'll be saving in the database so we're going to say it's going to be an integer and then since it's going to be a primary key each integer so each ID of each question will be totally unique from each other and then index equals true just increases performance and postgres a little bit when we're querying for a specific ID we then want to say question text because that's another column we want in our database equals a column and we're going to just pass in string and then we're also going to say index equals true here so this is going to be our first table within our database which is questions which has an ID in question text and now we want to go ahead and say class choices and we also want to pass in base here we want to say this is going to be named choices and just like above we want an ID for our choices which is going to be a column of integer where we can say the primary key is going to be equal to true and we want it to have an index which is also equal to true we want to have a choice text which is going to be the answer that we're going to be able to select where we can say column and inside here we'll pass in string and index is equal to true we want to say is correct which is going to be you know just the Boolean that says is this answer correct for the question and we can say this is going to be a column where we're going to be passing in a Boolean and we want the default answer to be false and then lastly we want to create a question ID which is equal to column and inside here we can pass in integer foreign key which is going to be the foreign key of a question so each choice is going to be associated with a question so we want this to be associated with a questions dot ID so again to recap we have our class questions which has which is going to create a table of questions with an ID in question text and then we're going to have a class of choices with a table of choices with an ID Choice text is correct and a question ID which is a foreign key that will link back to questions so awesome stuff all right so now we can close out of both of those and go back to our main.pi file and right now we want to import some things from our database and models so let's just go ahead and say we want to import all of models which is going to be our database tables and then we want to say from database import our engine and our session local and then lastly from SQL Alchemy .orm we want to import our session and that's going to be our session for our database okay so now under our app equals fast API we want to say models dot base dot metadata dot create all and we want to pass in our bind that is going to be equal to our engine from our database this line will create all of the tables and columns in postgres so now after we create these classes we need to create a connection to the database and we can do this by saying def get DB and inside here we want to say DB equals a new session local and we want to try something because it can fail so we want to say try yield DB and then we always want to say finally DB Dot close so we're always going to try and open it and then no matter what we will always close our DB connection all right so now we have our postgres string connected to our application we have our database and everything configured the next step is just going to be writing API endpoints for our entire application but before we do that we actually need to go ahead and create some annotations so we can say DB underscore dependency so this is going to be for a dependency injection equals annotated and we want to pass in our session and we want to say this depends on our get DB all right now let's go ahead and create our API endpoints so the very first one we will create is being able to create questions and choices for our application so we can say at app.post and inside here we can say slash questions and we want this to be called async Def and we're going to say create questions where we are expecting a question of type question base which is our pedantic model above for data validation purposes and then we want to say DB of DB dependency so we're passing in a data validation that's going to validate the body of the API request and then we're going to be able to create a connection to our database from our fast API application so this is awesome stuff all right now let's go ahead and just say DB question is going to be equal to our models.question and here we're going to be using some SQL Alchemy to write an orm statement that will link us back to a piece of data in the database and inside here we want to say question text is going to be equal to question dot question text we want to say DB dot add and we want to add our DB question we then want to say DB dot commit we then want to refresh it so we can say DB dot refresh and we can pass in our DB question again and now we want to say four choice in our question dot choices or we can say DB choice is going to be equal to our models.choices and now we need to pass in everything for our choices so inside our models.choices we can say Choice underscore text equals Choice dot which equals Choice dot Choice text is underscore correct is equal to Choice Dot is correct and then lastly we want to say question underscore ID is going to be equal to DB question dot ID all right so we're doing a quick filter for our DB Choice which we're going to be looking in our models dot choices and pass in some arguments for that object let's then go ahead and say DB dot add and we will add in our new DB choice we then want to say DB dot commit and that is really all we want to do for this so with all of this we've created our database tables our database connection strings and our first API endpoint let's go ahead and just open up our terminal and let's run our application [Music] and we can do this by saying ubicorn main colon app dash dash reload and I must have forgot to install uvicorn so let's go ahead and just say pip install uvicorn all right now let's go ahead and do the exact same command alright so now let's go ahead and open up our browser let's open up this post request and let's say try it out the question tax is going to be what is the best what is the best python framework we can say fast API which is going to be true and then right after this we can pretty much just say foreign all right let's click execute if we scroll down we can see that we get a status code of 200 with a response body of null and now if we go into our PG admin and we refresh our tables we can see that we automagically have choices and questions now created now if we click this query tool in the top left hand corner and I say select star from choices and I click this play button we're gonna get our two questions fast API and anything else which has a question ID foreign key of one and therefore if we come in here and we say of questions and we run this we're going to get what is the best python framework alright cool stuff let's go back to our application and let's go ahead and just write a few more endpoints thank you so now right above this post I'm going to go ahead and create a new um get request method to be able to fetch a question so let's go ahead and just say app at app.get and we will say here slash cool questions slash and right here we will pass in a question underscore ID or we can say async Def read question and we will pass in a question ID which is going to be equal to an INT and then we want to add our DB of DB dependency [Music] okay we're moving right along and now let's go ahead and just say result equals DB dot query and inside here we want to say models.questions Dot filter where we can pass in our models DOT questions dot ID equals our question ID that we're passing in as a path parameter and then we want to say dot first so it's going to get the very first record that it finds in the database now we want to make sure that result is not empty or none or null so we can say if not result we want to raise an HTTP exception where we can pass in a status code of 404 and we can say a detail which is question is not found and if it is found though we'll just return the result so if we go back into our terminal and we start up the application Again by saying uvicorn main cooler nap dash dash reload and we go back to our browser if I can find it if we refresh this we can see we now have a get request where we can pass in A1 and we're going to get a question text what is the best python framework with an ID of one and that'll match exactly what we have in our postgres database all right and let's just go ahead and do one more API endpoint for choices so right under our questions let's go ahead and just say at app.get and we will say slash choices this time but we want to pass in our question ID still so we're not going to get one choice we're going to get all of the choices for that specific question all right so now let's just go ahead and say async def read underscore choices where we can pass in a question ID that is of type int and we can pass in our DB of DB dependency all right and now inside here we want to say result equals DB dot query but the query will be a little bit different than how we did our questions um where we're going to say models.choices dot filter and we're going to pass in our models dot choices dot question ID equals our question ID that we're passing in and just like we did up here we can just copy this and paste it in here so if not result raise an HTTP exception of choices is not found and if they are found we will just return our result let's make sure our terminal is running which it is let's go back to our application where we can pass in a one here as well and we got a server error so let's see what's going on here oh okay and it's because I didn't say anything at the end we need we need to say dot all so our orm knows to fetch all of the records so now let's go back and let's just hit this again and now we're going to get all the choices for that question one so if we look at the question the question is what is the best python framework and our choices from postgres is going to be fast API which is true and anything else which is false so with this we just went ahead and created a fast API application using postgres and PG admin to save all of our records we just create an entire application super fast and that's the power of fast API if you enjoyed this video please give it a like and a comment and I will see you in the next video
Info
Channel: Eric Roby
Views: 12,591
Rating: undefined out of 5
Keywords: fastapi, python, postgresql, fastapi python tutorial, fastapi python, fastapi tutorial, pgadmin, sqlalchemy, fastapi postgres, fastapi postgresql, fastapi postgresql pgadmin, postgresql pgadmin, python fastapi, fastapi database, fastapi with postgresql, how to use fastapi postgresql, how to use fastapi with postgresql, how to use fastapi postgresql pgadmin, pydantic, fastapi pydantic
Id: 398DuQbQJq0
Channel Id: undefined
Length: 27min 37sec (1657 seconds)
Published: Sun Jun 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.