"video_title": "FastAPI Tutorial - Building RESTful APIs with Python",
  "transcript": "what's going on guys assalamu alaikum\nwelcome to amigos code in this video i'm\ngoing to teach you how to use this\namazing python framework for building\napis fast api was nominated as the open\nsource python library of the year\nand to be honest it's quite amazing\nbecause you can start building your own\napis in a matter of seconds\nso it kind of competes with frameworks\nsuch as flask and django and to be\nhonest it's quite cool\nso in this video what you're going to\nlearn is how to create this entire api\nright here where we're going to have a\nmodel called user and the user will have\nfirst name last name middle name gender\nand a list of roles and you'll see that\nthis data then we'll store it into a\nfake database and you'll see how easy it\nis for us to build\nall of these http methods get post\ndelete and put where the client will\nsend a request and then we basically\nhave the server right here so\nfast api uses the uvicon http server and\nit's very similar to\nexpress.js and node if you have done\nsome javascript and also it kind of\ncompetes with golang as well because\nit's an asynchronous server\nso yeah so what we're going to do is\nwe're going to have the client and this\ncould be any\nui or\nany other application that wants to\nconnect to your back end and you're\ngoing to learn how to build all of this\nso if i show you and right here i'm\ngoing to issue a request to localhost\n8000\nand you can see that this is basically\na json blob that we have but also under\nso in here under forward slash and then\napi v1 users have a look so all of this\nis actually coming from\nour back end build with fast api if\nyou're new to my channel go ahead and\nsubscribe give me a thumbs up so i can\nkeep on recording this video so\nliterally take two seconds and smash\nthat like button so i can keep on\nrecording these videos if you're not\npart of the amigo squad community go\nahead and join the community is growing\nand i would love to see you there both\non discord and the private facebook\ngroup without further ado let's kick off\nthis video\nwhat exactly is fast api\nwell fast api is nothing but a framework\nfor building apis it kind of resembles\nframeworks such as express\nand others in the golang world but\nbasically what they're trying to do is\nto bring some of that good stuff from\nthose frameworks into the python world\nso in here you can see that they say\nit's very fast and high performance\nfast to code\nyou can reduce about 40 percent of bugs\nin here\nvery intuitive easy short robust and\nthere is a set of standards already that\nyou can just\nfollow in order to build your apis so\nliterally as you see in this course\nwe're going to build a fully fledged api\nin a matter of seconds and it's going to\nbe really fast hence the name fast api\nso in here in this main documentation\nso here you can actually go and read\nmore about it um some of the options\nuh the installation process on and so\nforth but i will come back to this in a\nsecond now fast api is just a framework\nfor building apis in order for you to\nserve your api you need a server\nso for that it uses\nit uses uv cone and uv con is the\nlightning fast asgi\nserver and sgi stands for asynchronous\nservice gateway interface and basically\nit's intended to provide a standard\ninterface between async capable python\nweb servers frameworks and applications\nso in this course you'll see that we'll\nuse uv cone under the hood\nbut in here this is how you can install\nuv cone\nand configure the ports and you'll see\nsome of this stuff as well when we\nstart learning about fast api so right\nhere you see that they even have the\nlogo right here\nand what's really cool about fast api\nand uv cone is that they are ready for\nproduction\nliterally they are ready for production\nif you want to build production grade\napplications that\nreal users will receive traffic\nyou can definitely use\na fast api to build your products next\nlet's go ahead and install fast api\nand you'll see how we're going to build\nan api in a matter of seconds\nall right let's begin our journey\nbuilding this entire application right\nhere where we're going to use fast api\nand python\nso as i said fast api is just a\nframework for building apis and we still\nneed the uv cone http server which is a\nvery lightweight asynchronous server\nfor python so if i go back to the docs\nand in here you can see that they have\nthe installation process so pip install\nfast api\nand we also need to install the server\nright here\nright so for production they recommend\nus to use uv cone or hypercon but we're\ngoing to use uv cone in this course so\nlet's together install fast api and uv\ncone and build a really simple api\nso for this course i'm going to use vs\ncode so open up vs code and within vs\ncode i do have this diagram which you\ncan find the link for the repo where you\ncan find the source code including this\ndiagram so it's this one that you are\nseeing right here\nso let's together open up the terminal\nwithin vs code so new terminal and to\ninstall fast api is as follows so you\nsay pip\nand then i've got pip 3 or you can just\nuse pip\nand then install\nfast api\nand i also want to install uv cone so\nwithin quotes i'm going to say uv corn\nand then here i want the standard so\nthis will bring the minimal dependencies\nfor uv corn\nso here i've got a typo so this should\nbe uv\ncorn just like that press enter\nand there we go successfully installed\nfast api as well as uv cone\nnow let me close this terminal for a\nsecond and in here i'm going to open up\nthe explorer\ncreate a new file\nthis will be named main dot py\nnow within main.py i'm going to say from\nand then fast\napi\nimport\nand then fast api\nnext what i want to do is to create an\ninstance of the application so i'm going\nto say app\nequals to and then fast api\nand if you've done some express js this\nwill look very familiar\nnow what i need to do is let me just use\nthis annotation so i'm going to say at\nand then app dot get and this will give\nme a route\nfor a get request so here i need to\nspecify the path so here i'm just going\nto say within\nquotes for slash so this will be the\nroot and then here i'm going to have a\nmethod call it root\nand inside it's not going to take\nanything\nand right here i'm going to return\nthis object or dictionary and i'm and\nthen i want to say hello\nand then here i'm going to say world\nand it's as simple as this\nnow let me save this\nand open up the terminal and to run the\napplication we say uvcorn\nand then main column and then amp so\nmain is the name of our module so\nmain.py\nand then app is the instance of our\napplication that we've just defined and\nfinally what i want is to say dash dash\nreload so if i make any changes the\nserver will reload automatically so now\npress enter\nand have a look\nso we'll watch for changes in these\ndirectories so this is the directory\nthat i'm working in\nand then have a look uv cone running on\nlocalhost\n8000 and then at the very end you can\nsee application startup completed so now\nwhat i can do is if i open up my web\nbrowser\nand in here let me just say localhost\nand then 8000\npress enter\nand have a look so this is quite cool so\ni've got this json blob which is hello\nand then world\nso here if i so if i just\nclose this\nand if i change this to hello and then\nmundo\nand then if i\nsave this\nand then go back\nreload\nhave a look i didn't even had to\nstop and start the server because when\nwe ran it we told it to so here\nwe told it to\nso have a look we told it to reload\nand to be honest this is it\nand you can see down at the bottom we\nhave the\nlogs so this was a get request to the\nroot and the status code was 200 which\nmeans okay\nbefore we move on let me touch on http\nrequest methods and this will make sure\nthat you understand exactly what you're\ndoing moving forward\nnow http requests defines a set of\nrequest methods to indicate the desired\naction to be performed for a given\nresource\nso we have a list of them so if i scroll\ndown and you can find this link under\nthe description of this video but have a\nlook we have a get request and this says\nthe get method requests a representation\nof the specified resource\nrequests using get should only retrieve\ndata in here so if i go back to vs code\nhave a look\nwhen we say app dot\nget so this right here\nis our get http method\nand currently this is the path so this\nis root\nright so uh localhost a thousand\nand then the data that we return is this\njson object that contains a key hello\nand then the value\nmundo so if i go back to my web browser\nwhat i want to show you is in here\nif i uh right click and then inspect and\nyou can do this in any web browser\nand go to network\nand reload the page\nand have a look what we have we have\nstatus method\ndomain file\nhere this is a get request\nto localhost a thousand\nand this was the path so forward slash\ni can click on it\nand this gives me more information about\nit right so this was a gate request\nthe status was 200 okay\nthis was the http version that was used\nthis was the response headers\nand request headers in here\ni can have a look at the cookies the\nrequest but more importantly if i click\non response\nwe have the json object in here so if i\nclick on raw so you don't have if you\ndon't have the json extension you might\nsee something like this\nbut this is the response which was sent\nby the server so this response in here\nso\nthis is pretty much how it works and\nsomething which is really important is\nso if i go to headers have a look the\nstatus is\n200 which means okay so if i change this\nto\nforward slash and then foo\nenter\nso we have the status 404 meaning that\nit's not found because we haven't\nconfigured\nthis route just yet\nso if i close this\nand if i go back to localhost 8000 we\nhave hello mundo\nso this is a get request but we also\nhave other http methods we have head\nso asks for a response identical to a\nget request but without the response\nbody\npost this is used to submit an entity to\na specified resource\nso you learn about post\nput is used to replace all current\nrepresentations of a target resource so\nusually this is used for updating\ndata in your back end\ndelete\nthe delete method is used to delete a\nspecified resource\nconnect options trace patch so on and so\nforth\nso i'm gonna leave a link where you can\nread more about this but it's very\nstraightforward and in this course we're\ngoing to cover the most important ones\nwhich are get\npost put and delete\nbefore we carry on let me still teach\nyou about an important concept that you\nshould really be\nbe aware when working with fast api and\nuv core\nso as i said before the asgi\nspecification and if i click on this\nright here so this takes me to this\ndocumentation and an sgv and sgi stands\nfor asynchronous\nservicer gateway interface right here\nand is intended to provide a standard\ninterface between async capable python\nweb service frameworks and applications\nnow what this means is if i open up vs\ncode\nso if you are aware of the async\nawait keywords in either\njavascript or python then you will\nunderstand this\nsometimes we want to have this method to\nbe able to wait for\nan asynchronous computation\nso the way we do it is by using async\nand then let's say here we have to wait\nfor an http request so we can say await\nand then here this is like\nfull for example right\nnow obviously we don't have this method\nfull that will go off and get some data\nfrom the internet using asynchronous\nfashion but if you want to use the await\nkeyword\ninside of your methods you need to have\nthis keyword before the dev keyword for\nyour methods\nnow this is really important and this is\nwhy\nthis right here is an asynchronous\nservice gateway interface\nnow inside of the documentation for fast\napi they have a section on concurrency\nand a sync await\nso\ni'm going to leave this link where you\ncan basically go and read more about it\nbut async await is not something that\nwe're going to fully cover in this\ncourse but i just want to make sure that\nyou are aware of it\nso that when you see the a sync keyword\nused in methods then you know what it\nmeans\nso for this course we not going to need\nthe await inside\nhere maybe later\nbut at this point i'm going to use the\nasync keyword for all of my methods\nif you have any questions please do let\nme know otherwise let's carry on\nall right so for our application we want\nto be able to store a list of users into\nour database and then expose the api so\nthat we can get users get user by id\ndelete users update users so on and so\nforth so this is the model that we want\nto have right here you can see all the\nattributes for the user id first name\nlast name middle name\nwhich is optional gender and a list of\nrows\nso let's together define this\nin our application so back to vs code\nand in here let's create a new file and\ni'm going to name this as models.py\nand for this course we're going to use\npydantic so pydantic is a python\nlibrary to perform data validation we\ncan declare the shape of our data as\nclasses with attributes so let's define\nour class so in here let's just say\nclass\nthis will be user\nand this will extend base\nand then model and in order for us to\nuse base model we have to import so\nlet's say from pi and then dantic import\nbase and then model now inside of our\nclass we can define the attributes so i\nsaid that we want an id\nand the id will be optional so let's\njust say optional\nand this will give me the import from\ntyping optional and finally the data\ntype for this will be a uid and you\ncould choose for example an integer if\nyou wanted to but in my case i'm going\nto say you it and if it's not provided\ni'm going to say uid and then v4\nright here and make sure that you have\nthe correct imports but vs code is\nadding these for me\nnext i want to have the first name\nand this will be a string\nlet's do the same for\nlast name i also want to have middle\nname and this will be optional and\nfinally i want to have the gender and\nthis will be an enum so let's just have\nthat so this\nwe need to\nimport so from\nenum\nimport\nand then enum\nand now i can say class\nand this will be gender gender\nwe need to pass the string\nand then enum type\nand this will have two values so male\nequals two\nand then male and followed by female\nthere we go now to use it we just say\ngender in here so this is our type\nand let's do the same for roles so a\nuser can have\none or more roles\nso here this will be rows instead of oh\nactually role instead of gender\nthis will be admin and then maybe you\nwant the user\nrole and maybe you also have a student\nrole\nbut this really depends on the type of\napplication that you are building\nthere we go and to use the row we need\nto say roles so this will be a list\nof\ntype\nand then row\nand we need to import list right here\nfrom typing we also\nwant the list\nand it's as simple as this\nso now that we have our model right here\nand we actually are using pi dantic and\nif you want to learn more about pydantic\nyou can follow this link where\nuh you can learn more about the data\nvalidation and the settings that you can\nuse but basically we haven't done much\nin terms of validation\nbut you can use pyraminting to do all\nkinds of things to make sure that you\nenforce the correct validations so what\nwe have now\nis we have our user right here\nthat we can now store in our database\nand use it as a data store for our\napplication next let's build this\ndatabase right here which we're going to\nstart off with a list but if you want to\nchange to a real database that will be\nreally straightforward as well next\nlet's go ahead and build our database\nthat will store the list of users\nso we have the user model now let's\nbuild this database where we can store\nusers\nso let's go back to vs code and in here\ni realized that instead of models.py\nline 16 for the id we need to invoke\nthis guy right here so just like\njust like this so we invoke so that we\nget a uid if it's not provided now let's\nopen main.ui\nand inside\nafter the application so\nline three\nlet's go ahead and have the database so\ni'm going to say db\nand this will have a type of list\nand i'm going to import list\nand the type of the list will be user\nand also import user\nand this will contain\na couple of users inside oops not\nwarning but users\nso if i just scroll up have a look we\nhave the imports\nso list from typing and models from\nusers so this is the user that we've\njust created\nnow inside let's have a couple of uses\nso here i'm going to say\nuser\nand inside let's have one male and one\nfemale\nso here i'm going to say id and then\nthis will be\nuid and then version four\nlet's invoke this\nlet's also define the first name equals\ntwo and let me put this full screen\nthere we go so this will be jamila\nand the last\nname will be ahmed and let me put these\non your line\nso this is much easier for you to read\nnow here let's define the gender\nequals to and then gender\ndot and then female\nand i'm missing a comma here\nso female\nand we need to import gender so from\nhere we import gender\nand we also need roles so here let's\njust say that jamila\nshe is\na student right so we have roles have a\nlook admin user and student\nso here i can say square brackets and\ninside i'm going to say row\ndot\nand inside we have student and i need to\nimport role as well\njust like that\nand there we go\nso let's have a comma here\nand let's have a\nsecond user\nand this will be alex\nand then jones\nand he's a male and let's say that alex\nis an admin\nand also a regular user so dot and then\nuser\nso you can fine-tune these roles um\nto according your application but here\ni'm just trying to demonstrate how to\nuse a list and there we go\nnow one thing to bear in mind is that\nthe id will change every time you\nrestart the application but that is fine\nwe're going to fix this in a second\nso this now is our database have a look\nso we have the database it's a list of\nusers\nand currently it contains two uses so\nlet me also remove this\ncomma\nand we are good to go\nnext let's define a route to give us all\nthe uses that we have in this list and\nexpose it to our clients\nall right so we have the database which\nis currently a list\nwe also have the model\nnow let's have an endpoint\nwhere clients can send a get request and\nwe're going to use fast api\nto send data that we have stored in our\nlist\nso let's open up vs code\nand in here so you've learned about http\nmethods so again we need the get method\nso here at and then app\ndot and then get\nand here we need to specify a path so\nlet's say forward slash api forward\nslash v1 forward slash and then users\nnow let's have the async\nand then death\nfetch\nuses\nand inside we're not going to pass\nanything\nand now we can say return\nand then db\nso basically we're just returning all\nthe contents in our db so basically it's\na list of objects\nnow let's test this so i'm going to save\nthis\nand then open up the terminal and have a\nlook\nthe application reloaded and started\ncompleted\nand started successfully now if i open\nup my web browser\nand here before remember we have\nlocalhost 8000 and this says hello mundo\nand if i reload this still works but now\nif i say\nforward slash and then\napi forward slash\nv1\nforward slash and then users\npress enter\nhave a look\nso we get\nan array of objects and here check this\nout we have\nid\nso this is a random string or a uid\nfirst name jamila ahmed female\nand then rose she's a student\nwe have alex\nso have look alex\njones\nthe gender is male and he has two rows\nso you can see that this is really cool\nnow the reason why my output is\nformatted like this is because i'm using\nan extension for firefox so here i think\nit's called json viewer so i think it's\nthis one here\nand basically it formats the output as\nuh you see in here so go ahead and\ninstall this and it's also available for\nchrome opera and other web browsers but\nto be honest this is it so you can see\nthat this is really cool now one problem\nthat we have is check this out so this\nid ends with 6d\nnow if i\nadd a space and then save this\nand then go back reload have a look the\nid will change\nso now is six two so what i wanna do is\nto have these ids fixed\nso i'm just gonna grab this string\ngo back\nclose this and in here so instead of us\ngenerating the u width like this let's\njust say u it\nand then inside we can pass the u it as\na string let me get the other\nid\ncommand c\nand then instead of generating each time\ni'm going to say uid\nand then pass the\nid inside\nsave this\nif i go back now if i reload check this\nout the ids are fixed\nand to be honest this is it so you've\nsuccessfully managed to\nexpose an endpoint that gives you back a\nlist of uses\nif you have any questions please do let\nme know otherwise let's carry on\nokey dokey so we've managed to send a\nget request into our api and we get back\na list of users\nnow how do we add a new user\nso\nin here\nlet's together have\nyet another api endpoint and the whole\npurpose of it is to add a new user\nso\nafter the app.get so let's have yet\nanother endpoint so we're going to say\napp\ndot\nand then\nif you recall from the http\nvideo\nso if i show you again in here\nso we have get\nwhich\nis used\nto retrieve data\nwe have post\nsubmits an entity to the specified\nresource often causing a change in state\nor side effects on the server\nso\nhere\nthe resource\nis\nthe\nend point\nthat we're going to define in a second\nand then it submits an entity so we want\nto submit a new user so let's do that so\nhere i'm going to say post\nand the resource is\nthe same in here\nso you can have the exact same resource\nbecause the methods change so this is a\nget\nand this is a post\nbut they live under the exact same path\nso now inside i'm going to say async\ndef\nand then register\nunderscore and then user\nand this will take a user so i'm going\nto say user\nand the type of it will be\nuser so the user that we've defined\nnow this user\nis the entity\nand this is basically what we received\nfrom the request body and i'm going to\nshow you this in a second\nso now what we want to do is just say db\ndot append\nand we want to append\nthe user\nso the user that is sent\nand as we know the id is generated and\nwhat i want to do is return\nand here i'm going to say user\nunderscore id\nand then oh actually let me just say id\nso id\nand this is equal to\nuser\ndot\nand then id\njust like that\nso we basically register a new user and\nthen we send to the client the id\nfor that user\nso\nnow that we have the post request\nwe can't really test post requests by\nusing our web browser so from our web\nbrowser we can only send get requests\nnext let's learn how to send a pulse\nrequest to our api\nright we have our method that takes the\nuser from the request body\nand adds it to our database and then it\nreturns the id back to the client\nbut as i said we can't really test both\nrequests with our web browser\nwell we have two options one is\nso if i go to plugins so in here or\nextensions\ni can search for rest and then client\nso here we have a bunch of rest clients\nand this one called thunder client is\none which recently came out and it has\nfive stars so people seem to love it so\nwe can install it\nthere we go\nand in here if i close this\ni should have the client here so i've\njust clicked on these three dots\nand then thunder and then client and my\nfont is actually quite big so that's why\nyou can't really see it so if i just\nmake it smaller there we go\nand let me increase the font right here\nso now you can see that we have the\nthunder client rest client\nso if i click on it\nnow i can send a request so have a look\ni can say new request and\nbasically\ni can send a post request get request so\nhave a look get post put delete so let's\njust send a get request into our\napplication so that you see it works\nso here i'm going to say http\nforward slash column column local\nhost column 8000\nforward slash api forward slash v1\nforward slash users\nand if i send\nhave a look we get back a json\nor an array of objects so this is the\nexact same thing\nthat you see in here\nbut now we are using this rest client\nbut we can also send a post request\nso the post request looks like this so\nwe have to copy one of these objects\nand here\nlet's just say new request\nthis will be a post\nand the url will be the same so http\nv1 and then uses\nand now inside of the body\nin here\nthis is the json content that i want to\nsend to my server\nso if i paste that\nand remove that comma there\nso this now is the json\nobject that i'm going to send\nso let me just make this bigger like so\nso you can see everything\nand right here\nso remember from our\nmodel\ncalled user we don't have to send\nthe id so i'm just going to remove that\nand here let's think about someone so\nhere let's just say\nrita and then oliver so i'm just\nthinking about random names so anna\njust like that\nand right here she's also a student so\nthis is the payload which is going to be\nsent to our server now this right here\nis the request\nbody\nso this is the request body so have a\nlook body right and then the format of\nit is json\nnow remember so in here\nin our\nmain.py\nhave a look\nso let me just collapse this for a\nsecond have a look so this right here\naccepts a user\nand this is what comes from the request\nbody\nso the user has to have the exact same\nshape as our\nmodel right here so id\nwhich is optional first name last name\nmiddle name optional gender and a list\nof roles\nnow let me go back to this request\nand i can just say send\nnow watch what happens i send the\nrequest and we have a status code\nso 200 means okay\nso this means that we successfully added\nthis resource\nor this entity to our database so if i\nopen up\nthunderclient\nlet's send a get request so i'm just\ngoing to use this one here\nand\nbefore so this was the response\nwith two\nusers so i've looked two users but now\nif i send the exact same request\nthere we go now watch we have jamil\nahmed\nwe have alex jones but we also have\nrita oliver anna she's a female and a\nstudent\nso this was really cool so you can see\nthat how we used\nthis client to send a post request\nthe body was this json object then in\nour\nendpoint here so if i collapse this once\nmore\nwe got the user from the user body\nand then we added\nto our\ndatabase and it seems like i\naccidentally removed\nthis return id and then user id so let's\njust add it back let me save this\nand let me just go back in here\nand\nif i send a get request\nso you can see that i only have two\nusers because every time the application\nrestarts i lose the data\nbut now let me send the post request so\nreta again\nsend\nand now have a look\nso 200\nbut in the response we have id\nand then the id that was generated for\nreta\nnow let me send the request again\nto get all users\nand have a look we have rita in here\nso this is pretty cool if you have any\nquestions drop me a message otherwise\nlet me show you yet another way that we\ncan interact with our api\nso as you saw thunder client is really\ncool and powerful and we can basically\ninteract with our api\nthrough vs code right so let me just uh\nfor now just close this tab in this tab\nand what i want to show you is yet\nanother powerful way that we can\ninteract with our api so if i open up my\nweb browser\nand in here\nyou saw that this is our data coming\nfrom the back end\nand if i reload\ni think yeah we do have retail in here\nand that's because i haven't restarted\nthe server\nso in here go ahead and remove api\nand then v1 uses\nand then type forward slash and then\ndocs\nnow check this out so here you can see\nthat we have this interactive api\ndocumentation which is provided by\nswagger and this is given to us by\ndefault right so whatever endpoints we\nhave\nit will generate the documentation for\nour api\nnow what's really cool about it and let\nme just zoom out a little bit\nso here\nlet's check this out so here we have\ndefault\nand this is because we can actually\ngroup\nthese routes but currently we're not\nso we have root\nforward slash we have api v1 users\nwhich is a get request\nwe also have\npost request that allows us to register\na user\nand right here we have the schemas\nso we have gender\nrole\nand user and we also have http\nvalidation error and validation error\nwhich are given to us by default\nso if i open up user it tells me the\nproperties of a particular user and what\nfields are required so first name last\nname gender and roles are required and\nid\nand middle name are not\nso you can see that this is really\npowerful\nnow i said this is an interactive\napi documentation what do i mean well if\ni click on get\nhave a look it says it takes no\nparameters\nthe responses\nmedia type\nand right here and it has an example\nvalue with schema\nbut what i want to show you is i can\nclick on try it out\nand then i can say execute\nand now have a look\nso this was the curl request\nthat was generated so if you were to\ntake this curl request and paste it in\nyour terminal this would give you back a\nlist of people and you can see the\nrequest url\nbut more important have a look 200\nand then we have the response body\nand we have three people so we have\njamila alex jones and rita oliver so you\ncan see that this is really cool\nso if you want you can interact with\nyour api this way\nanother way that you can view the\ndocumentation for your api is so here\nlet me just collapse that\nand this is actually given by default\nright and it's interactive so i didn't\nshow you actually so let's try and post\nsomeone so it gives me\nthe example here\nbut let me just say try it out\nand the id\ni'm going to remove it\njust like that\nand then first name\ni'm just going to give things as default\nfor now\nand then just\nsay execute\nwe have the curl that was generated\nthe request url\nand then 200\nthis was the response body so this is\nthe id that was generated\nand you can see that it works\nso now\ni can collapse this\nsay get all users\nexecute\nand then check this out so here now we\nhave four\nusers so we have this\none right here which was the last one\nnow finally what i want to show you is\nso this is the interactive\ndocumentation provided by swagger but we\nalso have redoc\nso redoc\nis just the api documentation\nit's not interactive so have a look we\nhave all the endpoints so root fetch\nuses\nregister user\nand\nbasically my font is quite big but if i\njust make it smaller so you can see have\na look\nso it gives me root\nfetch users\nand then register user and it gives me\nthe schema have a look first name\nrequired last name\nso on and so forth and it gives back the\nresponses you can have a look at the\npayload you can copy the payload\nand the url is right here\nand you can also download this open api\nspecification so this is really awesome\nso there we go i've just showed you two\nways that we can\ninteract with our api we can use\nthis one right here\nor we can use within vs code\nthunder\nclient\nand to be honest they are both the exact\nsame thing\nbut this one has a bunch of more\ninformation about your api\nif you have any questions please do let\nme know otherwise\nlet's build another\napi endpoint\nwe can get all uses we can add users\nnow let's learn how to delete a user\nfrom our database through the api\nso let's open up vs code and in here let\nus say\nat\nand then app dot\nand then delete\nso let me show you\nin here\nhttp\nwe have delete\nused to delete a specified resource now\nthe way that we're going to\ndelete a resource is as follows\nso inside\nlet's have the exact same path so let me\njust copy this\njust like that\nbut instead what i want to do is say\nforward slash\nand then curly brackets\nand then user\nunderscore and then id\nnow\nthis is a path\nvariable and i'm going to show you this\nin a second\nso now let's have a sync\ndeath\nand then delete\nuser\nand this will take\nthe user\nand the score id\nthe type of it is a uid\nand let's have the following logic to\ndelete a user so here what we need to do\nis to loop through\nour database so i'm going to say 4 and\nthen user in and then db\nif\nuser dot id\nequals to the user id which is passed by\nthe path variable\nif this is the case then what i want to\ndo is\nsay db\ndot remove and then pause the user\nand it's as simple as this\nnow i need to return\nso this basically comes out of the loop\nas soon as we find the user\nnow there is something else that we have\nto do here but i'm going to cover that\nin the next video but for now let's just\nsave this\nand let's learn how to delete a user so\nhere let's use the swagger docs\nso here\nlet me just reload\nand you can see that we have delete\nlet me make this bigger and let's fetch\nall the uses so try it out\nexecute\nso we have two users right\nlet's try and delete alex so let's grab\nthis id\ncommand c\nand let me collapse this\ndelete\nand it gives me the parameters so have a\nlook i need to specify\nthe user id so i'm going to say try it\nout\npass the user id\nand now execute\nand have a look so this was the curl\ncommand but have a look at the request\nurl so localhost 8000 api v1 users\nforward slash\nand this is the\npath variable and this is the id that we\nget\nfrom here\nthis is the id that we get from here\nnow you can see also we have a 200\nstatus code\nso if i basically\nget all users so get\nexecute\nyou can see that now\nalex is gone and we only have jamila in\nour database let me show you how to do\nthe same with thunderclient so here\nthunderclient\nand i'm going to say new request\nthis will be a delete\nand we need the path\nso api if you want users and i need to\nget the id for jamila so let me just get\nthere we go so that's the\nid\nand let me go back to this new request\npaste it in\nand then send\n200\nlet's get\nall the users\nsend and have a look no one\nis in our database because we deleted\neverybody now one thing which is not\nworking quite well\nthat is if i\ncome back here for a second\nand i try to delete so i try to delete\nthe same person so with the same id\nsend\nhave a look this is telling me that it's\nokay 200\nbut i know for a fact that\nwe don't have anyone in our database\nright so we need to\nhandle\nthis scenario in here\nand that's what we're going to learn\nnext\nso you've just saw that if i send this\ndelete request\nthis will always return a status code of\n200 saying that\nthe request indeed worked well that is\ntrue\nbut that is not really what we want to\ndo\nbecause with http\nthese status codes they represent\nsomething\nso in here let me show you so in this\nlink which you can find under the\ndescription of this video\nit says http response status codes and\nindicates whether a specific http\nrequest has been successfully completed\nand right here it's grouped into five\nclasses so informational\nwhich is between 100 and 199\nsuccessful 200 299 redirection\n300 399 client errors\n400\nand 499 and then we have server errors\nwhich is 505.99\nso this is when something happens so\nthis is when something goes wrong in our\nserver this is when the client sends a\nbad request for example\nand this is for success as you've seen\n200 and if i scroll down\nso you can see that it's telling me all\nthese requests so what they mean\nso have a look successful responses 200\nthe request succeeded and it gives you\nmore information but what i want to show\nyou is\nso if i scroll down\nwe have 400 client error responses\nso the server could not understand the\nrequest\ndue to an invalid syntax so this is a\n400\n401 so this is unauthorized so probably\nyou've seen this\nand\nwe have 403 which is forbidden\nbut maybe you've seen this one quite\noften 404\nnot found the server cannot find the\nrequested resource\nso in our case\nwe know that\nthis\nuser is no longer present in our system\ntherefore\nwe should return a 404\nback to our client saying that the user\ncannot be found\nso how do we do that with fast api let's\ncarry on on the next video\nso let's go back to vs code\nand let me just open up\nso i'm going to close this tab\nand i'm going to open up main.py\nput this full screen\nand right here so you saw that if we\nfind the user we delete the user\nright here and then we return so return\nmeans\njust pretty much exit out of this\nfunction\nnow what i want to do is so after the\nloop if this condition is not met\ni want to raise\na\nhttp\nexception\nand we have to import http exception\nfrom\nfast api so here\nhttp exception\nand i don't think we need this uid so\nlet's just get rid of it\nand if i scroll down\nso here\ninside we have to pass a couple things\none is the status\ncode\nand this is a 404\ncomma\nand then the detail\nso this is the message that the client\nshould see\nso in our case i'm going to say\nf\nand then i'm going to say user with id\ncolumn and then pass the\nid so user\nid\ndoes not exist\nand if i save this\nso you can see that this\nnow makes more sense right so if the\nuser doesn't exist\nthen we should tell the client what has\nhappened instead of just saying every\ntime\nokay that your request was deleted so\nnow if i open up this tab\nand if i send this delete request\nhave a look what's going to happen so\ninstead of 200\nnow we get 200 and that's because the\nserver restarted therefore we have\nthe data back but now if i send it a\nsecond time check this out so you see\nthat\nuser with id\nand then this is the id does not exist\nand this time we have a\n404 not found\nso this is exactly what we want\nso i'm going to leave this link for the\nhttp status codes so you can go and read\nmore about them but really all you need\nto remember is that there are five\ncategories\nso in here informational success\nredirection client and server responses\nthis is all for this video if you have\nany questions please do let me know\notherwise let's carry on\nokie dokie soho time for your very first\nexercise so you've seen that fast api is\nreally straightforward and awesome and\nyou can build apis in a matter of\nseconds now i want to challenge you\nwhere i want you to implement the port\nmethod and put method allows you to\nupdate an existing resource\nin your\ndatabase so what i want to do is go\nahead and create a model that allows you\nto update the first name last name\nmiddle name and rules\nand make sure that all of them are\noptional then create a new route with at\napp dot put and then using the same path\nthat we've been using\nand then receive that model and then go\nahead and write some code that if any of\nthose fields are not none\nthen update the existing user right and\nalso you need to make sure that you use\npath variables i'm going to leave the\ninstructions under description of this\nvideo so that you can follow along\nbut go ahead and challenge yourself and\ni'm going to give you the solution in\nthe next video\nall right so for this solution what i've\ngone ahead and done was i created this\nclass called the user update request\nthat extends base model\nand first name last name middle name and\nroles are\noptional\nthen inside of main.ui i do have this\nmethod called updateuser\nand the annotation that i've used was\napp.put\nthe same path for the other ones and\nhere i've got a path variable\nthen i take the user\nupdate\nand the class is user update request\nand also the user id from the path\nthen what i do is i check whether\nthe user is in our database\nso using a for loop in here for user in\ndb\nif the ids match then all i'm doing here\nis i'm checking whether the update the\nfirst name is not none so if that's\nthe case\nthen we update the first name\ni do the same for user update last name\nmiddle name\nas well as the rows\nand at the very bottom line 61 i do\nreturn because everything was fine\notherwise\nif\nthe user is not found i just raise http\nexception passing the status code 404\nand the detail message user with id does\nnot exist\nnow let's test this out so here make\nsure that you have uv coin up and\nrunning so if i open up the terminal\ni'm gonna run this command because i\nstopped the server\nand let me close this\nnow let's open up fast api\nand let's test this out\nso new\nand let me just copy the request from\nhere so i'm going to grab all of this\nand if you don't remember so if i do a\nget request send\nyou can see that we have\nuh two people right\nso let's update jamila ahmed in here\nso let's uh basically go to this new\nrequest\nand let me paste that and change get to\na put\nthis is jamila's ahmed right here so\nending five six two\nfive six two now the payload that i need\nto send\nto my new\nrequest is this one user update request\nfirst name last name middle name in rows\nso let me just copy this object in here\ncommand c\nand i'm going to go back to this tab\nand inside of body i'm going to paste\nthis\nand for jamila\nso right here let me just put this\nbigger\nand i don't need to pass the id\nso\ngender as well\nand here let's just give her a\nmiddle name\nso let me just say hello for example so\nyou see that it's been updated\nand for the roles let's also give her\nadmin\nand\nlet's just remove\nfirst name and last name right here and\nnow if i send this request so let's send\nit\nand have a look we have a 200 status\ncode which means okay\nand in here if i now get all uses\nyou can see that we changed jamila\nmiddle name before was null now it's\nhello and also have a look at the roles\nright so she's a student as well as an\nadmin\nso let's also change uh jamil ahmed to\nuh so here instead of saying jamil ahmed\nwe'll just say we want to update the\nlet's just say last name\njust like that\nto\nali for example\nsend\nand then go back\nand then have a look we updated the last\nname\nso you can see that this is working\nbeautifully also if i basically change\nthis to 3\nwe should get a 404\nhave a look 404 user with id\nending in 563 does not exist\nand also if i add in a comma here\nand let me just say 2\nand then send this\nso 442 so this is a bad request from the\nclient so the range is within 400 so 422\nand you can see that this is working\nbeautifully\nif you have any questions getting this\nfar please do let me know otherwise you\ncan grab this source code from the\ndescription of this video that's all for\nnow catch me on the next one\ni hope that you made this far if you\nenjoyed this video go ahead and give me\na thumbs up next week what i want to do\nis i want to build the front end for\nthis api so you'll see how to build a\nfully fledged full stack application\nusing fast api as well as react\nalso you saw that in here we kind of\nhave a database which is a list\nbut with what you have you can take\nthe code and then change it to connect\nto a real database so i'm going to leave\na link where you can go and learn about\npostgres so i've got a four hour course\non postgres and i'm also going to leave\na link where you can learn how to\nintegrate fast api against a real\ndatabase it should be really\nstraightforward if you want to gain a\ncertificate for this course go ahead and\nenroll on my website where i'll give you\na certificate for free where you can\nshow to employers\nif you're not part of the amigos code\nplease go ahead and join the communities\ngrowing both this discord and the\nprivate facebook group and let me know\nwhat other videos that you want to see\nfrom this channel\nand that's all for now i'll catch you on\nthe next one