Fast Api with Mongodb | Fast Api Tutorial |FastApi in 30 mins | #fastapi #python #mongodb #tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we are going to create a fast API app and we will use mongodb as a database so welcome to my channel my name is Rahul let's get started with coding so first let's create a directory and then we will create the python environment as well mkd and then fast API CD right and inside this we want to create our python environment as well so Python 3 then we have hyphen m v EnV and V EnV yeah our environment is also created let's open our code editor so code dot okay so let's activate our environment first for that source to V EnV then bin right and inside this we have our activate so this has activated the environment now now let's install all the dependencies so here we are going to use first fast API then uvon and then we use Pongo so let's install all these three so pip install fast API then we have UV con and next is p we are going to use P for connecting it with our mongodb cluster so by right so all are dependencies are installed so now let's start coding for this let's create a new file named main.py so main.py and in this first let's import fast API app so we can write here from Fast API import fast API and further we have to initialize an app with this so we can write here app equals and then fast API and save this now let's write a get request and we can use this as our homepage so for that we have to write at app doget and in this we need to pass what string will be our homepage so let's keep it slash only for now and this is going to be as synchronous function so we can write here async and then we can write diff and let's define the name so let's keep it as homepage okay and and this will simply return a message message and just write here hello world right and let's save this now to run a fast API app we have to use uvon so let's clear the console and write here uvon and then inside main we want to use app so this is our app here so we can write her main colon app and also we are going to use reload option here because we want to reload this page every time we make some changes so we can simply write hyphen hyphen reload right and let's see so here we can see our server is on let's go to our web browser and see what we are getting at this Local Host 8,000 right so we'll simply paste the path and yeah let's test this here here we can see as expected we are getting message and hello world so this was very basic of fast API now let's move and connect our first API with mongodb cluster for that we have to first create our mongodb cluster let's go to mongodb's official website I'll provide the link in the description right so we'll quickly log in with our Google so we'll use Google here I accept and submit now we have to fill all this form so I'll just quickly do that so let's keep AI model for now and just pick anything now in this we are going to use this m0 because this is a free model and let's go on this from provider we are going to select AWS and it will automatically select our region currently I'm in India so it is showing here Mumbai so yeah let's and let's give the cluster name so we can pass her voder and I think it's all set let's create this cluster we can simply click on this finish now from here we get an option to add data or we can use load sample and data modeling so if you are new and you want to perform crud operation you can use load sample data and mongodb will provide you a set of documents using which you can learn mongodb but here as we're using it in our app so there is no need to select anything from this now we can directly click on this connect here it gives option to where we want to use this MB cluster so right now we want to use it in our code so we have to go with this drivers so click on this and we can select python from here let's keep this as it is now let's copy this because we have to install this right so let's go and install this in our fast API right we can simply paste and run this and install SRV okay so it has already installed so no issues right and let's restart our server I have closed hit to install this right so server is working fine so in third step we can see we have an option view full code sample so let's click on this and copy whole code from this and paste it in our app so let's let's create another file name configurations so configurations dop and inside this we'll paste the code and we'll remove all this unnecessary code because we just want the database so this is a code which connects our database cluster with our app now let's create the database and its collection so for that we can write DB equals client2 DB so this will create the database and further we want the collection to be created so we can write here collection collection equals DB and in this we want to create it so let's write here too and data so this code will create a collection named too data now let's write our models for to-do app so for that we'll create a folder named database and inside this will create a file named models.py okay and in this models.py we are going to use penic first because this penic will help us validate all our data that is going to be saved in our database so from penic import base model now let's quickly Define our to-do class for that we we can write her class and then Todo this is going to inherit the base model so we can write her base model and further we are going to define the model first thing that we need here is the title so we can write title and this is going to be of type string then we have description and this again will be of type string after this we have whether this task is completed or not so for that we are going to use is completed and this will be of type Boolean and let's define its default value as false so we can simply write here false copy this and let's define is deleted here we are going to use this is deleted field for soft deleting the data now we have all these field along with this we are also going to update and create the de now along with all these fields we also going to update and create document for that let's define the timestamps as well so here we can write creation and this is going to be of type int we'll store the Epoch time here this will be equal to int and we can write here date time so we have not imported it right now so let's import it first so from datetime import date time and here we are going to use the Tim stamp function of this so date time. timestamp and in this we'll pass daytime. now so this will save the time stamp with default time stamp right let's copy this and paste it again rename this as updated at and save this information now let's define the schemas for this using which we are going to communicate with our database so we'll simply write here schemas right and in this we are going to Define two functions first is individual ual data and this will take the to-do now in this we are going to return all our data in dictionary object right so first we have is ID as mongodb stores the ID in form of object ID so here we are going to typ cast it first and then we'll use it and after this we are going to give the title and for title we are going to take this from the too itself then similarly for description and then we have the status and status is is completed or not so this will be the individual data every time we fetch something from the database we'll get only these many objects from it because at times we don't need all the information we just need data that the user is interested in in that scenario this comes in the picture and after the individual data and after this we are going to give the list data so that will give all the data from the documents and convert it into this dictionary objects right so let's define that function as well and we can write here all data and this is going to take all the todos and here we can simply return a list and we can do list comprehension in this this is going to return this individual data we will pass too inside it and this Todo is for too in todos so this will iterate this todos and after that it is going to create this dictionary and we'll and return the same in a list so we'll save this information and now we are all set to write the apis so let's go back to the main app so now let's remove this because this was just for the testing purpose so we can remove it so yeah and along with app we also need app router let's import the router as well so we can write here API router we also have to initialize it so router equals API router now at the end of this file we have to include all these router to this fast API app so let's do that here app do include routers and in this we'll pass router so let's copy and paste it here so now let's define the get request and in this get request we are going to return all the todos that are stored in our database so for that at router. get and we have to define the path so let's keep slash here and now we can Define the function so this will be asynchronous function async def get all todos and this will not take anything as an input now to fetch everything from our database we have to import The Collection here so from configurations import collection so now let's write a query that is going to fetch everything data equals collection do findind and if you pass blank in this find it is going to return everything and if we add certain queries like if we want to fetch on the basis of IDs we can pass it here and in that scenario it will just return those documents which satisfies that condition but here as we want everything from it so we'll pass blank and then here we can write return and we will use the schema that we have defined here so in this scenario we need all task because we have the todos here it will return return a list of documents so let's go back and here we can write return and we'll paste the function it is not imported so let's import it as well from database dot schemas import all tasks and in this we can pass in this data right let's save this as we don't have anything in our database right now so it will not return anything let's define the post function and then we can go on the Swagger page of fast API and we can check everything there right so let's define the post here so for that we have to again Define a post request at router do post and let's keep this also as slash so its path is also slash now we have to define the function this is also going to be async function So async Def and create create task so this is going to create a task here let's remove this colon from here so in create task we are going to get the data right so this data has to be of type too that we have defined in this model right for that we can write here new task and colon too as this is also not imported from our models let's import this so for that from database. Models import too now we have to create a Todo task using this new task here we'll write response equals collection dot so here we want to insert only one object so we will use mongodb's insert one function so collection dot insert one right and and this will pass in this new task so we'll just simply copy and paste and this has to be a dictionary object so we'll simply pass it to dict now let's put this inside try and accept so we can write try and here we have to write except exception as as e right now to send this error message we have to import HTTP exception so let's import it from Fast API itself so HTTP exception and here we can return HTTP exception and in this we are going to send status code AS 500 and then detail as F string so in this F string we'll Define that error has occurred so so some error recurred and then we'll pass in the error message here so simply write e so now if this inserted one query works properly it will return us a inserted ID so we have to return that to the user and if something went wrong and some error occurs in that case we are handling it in this exception case Okay so if everything is Success let's define the return here so return and in this we can pass in a dictionary and first will be the status code so and code this is going to be 200 because this is a success then we have the ID that needs to be returned so we can simply say ID and this will be resp do inserted ID so resp do inserted ID and this has to be part this will be an object ID so we have to pass it to string so let's pass it to string right St Str and save this so now let's go to our Swagger and verify it so so this is our normal Local Host 8,000 and here we can see we have an empty list so this is returning an empty list because we don't have currently anything in our database so let's go to the docs which is the Swagger for fast API so/ Docs and here we can see all our apis created so let's go to post because as saw earlier we don't have anything so let's try this out in this we can write fast API and here in description we can write tutorial all this are the default values so let's send this request so execute correct here we can see we have got our object ID so with this the new document is inserted now let's verify it through our get request so let's close this now from get request let's send this and see try it out and execute so it gives some error let's check the error what is wrong with this so here we can see we are using name in the to-do so let's go back to our schemas and change this name to title right and save right now our server is working fine let's go back to swag and verify so simply click on execute here we can see our first task that is created and it shows the status as well that it is false right now which means it is not completed and description and title are also present so this way we have completed create and retrieve operations let's go and write the update request as well now let's define the update task function which is going to edit our task this will again be a sync function so async and diff update task in this we will pass first the task ID so we can write here task ID this is going to be of type string and then we are going to pass the updated task which is going to be of type too so updated task and here we can see we have not defined the route for this so let's copy this and Define the route for update task as well so this will be a put request and in this we are going to take the task ID so we'll pass here task ID and same task ID is going to be passed here so this will be string now let's define the function so here again we're going to use try accept and let's write accept as well right and just write pass for now now to update the task we have to first check whether this task ID is proper or not so for that we have to first pass it into object ID and then we'll fetch document with this if that document exist then only we are going to update it otherwise we'll return error to the user so for importing object ID we have to use Basin so from Basin doob ID import object ID and here we can write ID equals object ID and in this we will pass the task ID here so task ID and now we can search for the existing document so we can write here existing and this will be collection dot find one and in this we can write ID colon and ID also we only have to find the non deleted entries as we are soft deleting entries in this so we have to write another query which will be is deleted colon false and this will be again in quotes so we can write here if not existing doc which means existing document in that scenario we will return an error so we can just copy this part from here and paste this so this will be 404 because we don't have that particular document so we can write here task does not exist task does not exist and if this exist in that scenario we are going to update it so we can write here resp equals collection. update 1 this is another function from mongod using which we can find a query and then we can update it accordingly so simply we can write her collection do update 1 right and in this will first Define the query that is ID and this will be equal to ID colon ID and this takes the next argument with what we want to update so here we are going to create another dictionary and this will write dollar set and this we we can pass in the updated task so we can simply copy this and paste here and this again has to be passed to dictionary so we can write dict here also in our models we have defined updated ad so let's define this here as well so for that task dot updated at and this will take the current Tim stamp so we can write here date time dot now uh we have to import date time as well so we can write from date time import date time right and save this now in our models we have set this updated at as an integer field so let's convert it into time stamp so date time. timestamp and we'll then pass in this date time do now at the end and we are going to return if everything goes fine and we receive a success response in that scenario we'll simply say return and here again we are going to pass in another dictionary with status code AS 200 and comma and we can define a message here that is Task updated successfully task updated so now let's define this exception as well so let's copy this code from here and paste it okay and save now let's go back to our Swagger and verify this request we'll refresh the Swagger and now we can see that after get we have this put request so let's first run the get request to get some ID from there right so we'll just copy the first ID that we have and then input request let's try this out and here we can pass in the task ID and in updated one let's passer fast API tutorial and in description we can write create tutorial okay and now let's test whether this is working fine or not so execute right so on executing we find that it says task does not exists let's go back to our code and see why it gives this error now here in this code we can see that we're using ID that's why it was giving us the error task not found instead we have to use underscore ID this is my bad right so we'll update it here and also at place of update one we are using ID let's replace this with underscore ID and save this function and let's check this again right so let's execute this we see that task is updated successfully right so now let's go back to the get request and check this also so try it out execute and perfect so here we can see our title is updated along with the description and this is how we have completed our update task as well now let's move and write the last operation that is the delete operation so let's go back to the code and here again we have to write another function so let's define the routes first so at router and Dot delete and its rou is is going to be again kind of same as the put API so slash and in this we are taking the task ID so task ID and let's define the function this is going to be async again and async diff and we can write here delete task right and in this we are going to take the task ID itself so task ID and this will be of type string in this scenario also we're going to first check whether this task exists or not this delete request is also going to be kind of same as our update request so let's copy this fully and we'll paste it inside this delete request right and what needs to be changed in this is that here we don't need this updated task so we can delete it now in this update one we are going to pass is deleted as true as we are using soft delete method so here we are going to only update a key which says is deleted true and here we can pass in is deleted [Music] as true right and save this here we can say task deleted successfully right and suppose if you want to delete this permanently from your database in that scenario instead of using this update one you can simply use delete one and that is going to delete it from the database but it is a good practice to use soft delete instead of hard delete that's why we are using this is deleted as true to just soft delete the documents now let's verify this delete request and see whether everything is working fine or not so let's go back to our Swagger let's reload this first now in this get request if you see we only have one entry right let's create a dummy entry right now with this try request so we'll execute this right now we see this is created so let's copy this ID now let's go back to our get request and see whether it is created or not so we'll execute this again and here we can see we have created it multiple times so let's delete the last entry that that is present so we'll copy this and go to our delete request here try this out and in this we can paste the ID that we have copied let's execute this so this is Task is deleted successfully now as we know that this task is deleted now let's red delete this and see what exactly our app does so we'll execute this so now this time it says task does not exist because we have handled this case in our code itself now at the end let's again go back to our get request and see we are not getting the deleted entries so first refresh this and in the get request here we can try it out and execute here we can see we are getting all the entries which means that we have not handled the soft delete method so let's go back to our code and solve this here in the get request we can see we are considering all the requests so here we can see we are simply writing find instead is deleted false undor deleted and we can write false here so this will fetch only those documents which are available to us and go back and re-execute this now in this scenario we only get two IDs which means now we are properly handling the delete scenarios as well so this was all about the fast API so in this way we have successfully created API for all our crud operation that was create update retrieve and delete right now I hope by end of this tutorial you are able to create your first fast API app and use it in your project as required if you like this tutorial don't forget to hit the Subscribe button and comment down below if you want more tutorials like this thanks for [Music] watching [Music]
Info
Channel: Witty Coder
Views: 1,112
Rating: undefined out of 5
Keywords: Fast Api Mongodb, FastApi in 30 mins, Fastapi mongodb, witty coder, fastapi mongo db, fast api mongo, mongo fastapi, mongodb fast api, FastAPI MongoDB connection, MongoDB with FastAPI, fastapi mongodb, fastapi with mongodb, fastapi nosql tutorial, fastapi mongodb tutorial, fastapi nosql db, fastapi nosql database, fastapi in mongdb, fastapi mingodb, mingodv fastapi, fastapi mngodb, fastapi mpngodb, fastapi monhodb, hastapi mongo, fastapi and mongo, mongodb fastapi
Id: J7SXGbShbj8
Channel Id: undefined
Length: 28min 34sec (1714 seconds)
Published: Sat Feb 24 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.