FastAPI - A python framework | Full Course
By Bitfumes
Summary
## Key takeaways - **FastAPI's Auto Swagger UI**: FastAPI provides automatic Swagger UI and ReDoc docs by default, letting you test API endpoints without Postman. [00:33], [00:44] - **Path Parameters with Type Hints**: Use curly braces in paths like /blog/{id:int} for dynamic routing; FastAPI auto-converts strings to integers and validates types. [31:41], [35:42] - **Pydantic for Request Validation**: Pydantic models define request bodies with type hints; FastAPI auto-validates incoming data and generates schema docs. [58:38], [01:00:02] - **SQLAlchemy ORM Integration**: FastAPI uses SQLAlchemy for database ops; define models extending Base, then use db.add(), db.commit(), db.refresh() for CRUD. [01:21:45], [01:37:08] - **JWT Auth with OAuth2 Scheme**: Protect routes with OAuth2PasswordBearer dependency; verify tokens via get_current_user to extract active user details. [03:28:37], [03:36:24]
Topics Covered
- Full Video
Full Transcript
hello and welcome to the fast api course this fast api is a super fast python web framework there are other frameworks
like django or flask or maybe other but fast api is very very modern and it has a very nice feature of a synchronous programming
which is still lacking in django framework so let's see how this fast api is going to make your life easy by having lots of features
so first the very best feature i really like is automatic documentations whenever you create an api then how you are going to check them
generally we use the postman but that's not a good thing so by default fast api provide you the swagger ui this is a very nice ui where you can
simply check what are the routes we have created or api endpoints you have created not only that you can also
try them out check what is you are creating how it is going to respond if you don't like the swagger ui first api provide you another
nice re-dock ui this is the same but having a very nice and minimal design for the documentation so automatic documentation is the best
thing for the fast api next i really like that since this is a modern framework it also uses the modern features of python
it uses python 3.6 and more and using the pidentic library this fast api provides you the typing system that means you can type hint
the variable and other things like here we can see that user id should be string or maybe id should be the integer so these kind of things you can achieve
with the fast api because it is modern and using latest python next important feature is it is totally based upon the open api and
json schema so open api is a linux foundation under linux foundation and it defined actually how you create your api and
since it is based upon this open api standards you are going to create the api in a very recommended way or standardized api
it also has the json schema that means it's it by default return json which every modern api need to communicate with other things so
that's how it is so great next important feature is the code editors autocomplete yes fast api has the auto complete
feature in vs code also if you like to use the pycharm then in the python also it's going to complete the autocomplete the code you are
writing using these ids and this again achieved by the use of the typing system
using the pedantic library of python so that's why it's very very important to auto complete things so that you can write
fast api really fast next important feature is this security and standard yes fast api provide you http basic security
is the oauth 2 with the gwd token you can send the api token header query cookies etc so that's an amazing feature other than that we have a dependency
injection unlimited plugins testing you can test your application no need to have any different library it has its
own system yeah it uses pi test to test your applications since fast api also uses starlet starlet is a
another framework of python but since this fast api is built over this starlet and starlet provide websocket support graphql support
in progressive background task startup and shutting down of events that means all these things are available in fast api
this starlet has provide other features just like these but everything is now available in fast api no need to learn any other thing if you have a previous knowledge of starlet that will
be amazing next other supports for sql database nosql database and graphql so you can see the first api is really a
package of full web framework so what we are going to learn in this course we are going to get a start with the
fast api that means how we can install and set up things how we can understand the basic structure of fast api then we will land upon some
basic concepts like path parameters and api docs for swagger and redox how you get the query parameter how you perform the request queries
then we will move to the intermediate concepts like debugging your first api application then pidentic schemes what are these pedentic schemas what are they how you can use
the sql alchemy to connect to the database then how we can create the models and using that model create the table in our database
so that will be used by the sql alchemy ora next we will going to talk about the database task like crude related things for the blog like storing getting updating and
reading all these things we will do in the database part then we will talk about some responses how we can handle the exception and return the
response and how we can define the response model so that we can only show certain fields which we only want like we don't want to show
the password of the user so how we can restrict that thing using the response model next we will going to talk about the user and the password so first we will create the user
then we will hash the password uh using the decrypt algorithm and then we will going to show the user and defining the documentation tags that's
amazing feature next is a great thing called relationship since we are using sql alchemy and sql can we provide the relationship between the
blog and the user so we are going to create the two-way relationship in fast api next we will going to talk about the refactoring for the bigger application so yes we will going to start the
application in a very funky way wherever we we want we write the code but later we need to refactor it for the different different thing like first we will go
and create the routers and then define some parameters for the routers this is going to be the proper structured application next we will talk about the
authentication using gwt jwt stands for json web token so first we will create a login route where we can provide the username the
password then we will verify the password using the hash algorithm then we will return the jwt and move all other routes behind the authentication
and finally we are going to deploy our application using data dot sh website isn't it amazing so let's really see what will be the
final product we were going to have so this is the final product of our application this is a fast api swagger documentation
and we can also check this same thing with the redox and not docs just re-dock and this is going to have our application you can see authentication route blog
routes user route i like to have the swagger one which is uh more like a friendly one so you can see we have all the blog related routes
behind the authentication we have this lock and if we try this out it's not going to execute and if we try it says hey you are unauthorized if we
return a four zero one status code with a nice message but that only happened after we authenticate the user so swagger provide a very nice
authentication system so let's log in here using this email and the password we have defined and now you can see
these logs are visible or you can say active and this means now if we try to execute the same route we are getting the blocks with
the relationship we have created for the creator we are getting the data for the creator so everything is there that's amazing so yeah we have this kind
of structure for login we can try this out by providing the username here and in that way we will going to get in return
the gwt token so if we try it out click on execute you can see we are getting this access token this is a really long jwt token
which is having a type of bearer okay so that's saying we are also having final thing which is called user and you can see we have this
doc tags and these are we have defined and everything is here so this thing is going to be really fun and amazing and let's see
how we can build this api thing using fast api and first thing you need to know is this person sebastian is the creator of fast api
you can see this is the github repository and his github repository name or github username actually is tangolo i don't know what's the meaning of this but that's
cool so he has created this fast api and you can see this is a python framework for creating a fast api that means first api high performance easy to learn yes this is
extremely easy to learn fast to good ready for production everything 26.6 for now obviously it's going to increase 1.8
k i think branches no not branches folks i think yeah it's folk okay so this is the fast api you can say github page and if you want to visit this
uh how you can get it simply say fast api on your google and then the first thing you will get is fastapi.tangolo.com
fastapi.tangolo.com you can simply click here and it will land to the you can say the document or maybe the landing page of fast api that's cool everything is same
so this is the github repository this is the creator and this is the website since first api is a python framework that means you need python
obviously but that should be or that must be actually greater than 3.6 version of the python so let's see what version of python
i have so if i just say python hyphen hyphen version you can see we have 2.7.16 which is not good
but actually i had python 3 and if i check python 3 yes it is 3.8.2 so 3.8.2 is there that means if i need
the pip so i need to use a pip3 and if you don't have that that means the python 3.6 and greater than that then you just need to
search python and you can easily install this python on your machine by going to this and download 3.9.1 or whatever the latest version of python is
when you have done with that you need to install your fast api on your machine yes you can install it globally or you can use the virtual environment
and if you don't know how to create a virtual environment you can simply search v-e-n-v in python and actually that should be v-e-n-v yeah
google is smart okay then you can go to this documentation and it's very easy python 3 because we have a python 3 then we can give this mode
which is going to be creating virtual environment and you can give the name simple and if we are here on the terminal i can say python i need to create
the venv so v-e-n-v then i need to give the name and i give i can give the fast
api env okay once i have created that then you are going to see we will have a new directory called fast api
env inside the folder where i have run this command so i ran this command on the fast api tutorials directory which is this one and inside we have a fast api env
cool next we need to activate this one so how we can activate on the mac os this is that one and on the windows you need to just run this file so we need to say
source the name bin activate cool so source and after that we have a fast api env slash
bin slash activate run it and now you can see we have this fast api in the parenthesis before all these things so that means we are inside of the environment
how i can show you that this is a correct thing simply i'm going to say pip 3 install fast api that's how we install
the fast api in our machine or simply in our environment once we have done with that we are going to hit enter and it's going to install the fast api
on your virtual environment only and now you can see it's done and it says you have a older version of pip so you can
run this command to upgrade it so simply run this command to really upgrade the pip version for the python 3. okay that's also done
after installing the fast api and upgrading the pip version next task is to install the uv icon so you can use the pip install uv icon
standard version if it's not on your system you can generally use this normal version so since i have python 3 so i can use the pip
3 then i say install uvi uv icon hit enter and it's going to collect and install it
so easy that's done actually so i told you that we are on the virtual environment so we have installed the uv icon and if i try to get the version
of this one you can see we are having 0.13.3 but if i open the terminal without having any virtual environment
then if i try to run the version of it you will see it says not found because this uv icon is only installed in the virtual
environment so when you are not in the virtual environment then uv icon is not available so if you are not using virtual environment that that totally doesn't matter it's just the
preference and if you are not using virtual environment it will be available globally okay so here i am on the vs code and i am inside the directory
where i have the fast api environment okay so vs code is smart enough to detect this is a virtual environment so once i open the terminal it's actually
going to move me into this environment so if i delete this terminal and create a new terminal
you can see it's actually activating the for the virtual environment so that's done what next we have to do we have the vs code ready
let's go here after installing the fast api after installing this uv icon next we need to create the main dot py file
okay so create the mean mean dot py file here we need to import the fast api so from fast api
here we have the auto suggestion because vs code python extension is installed import we want to import fast api that's very important
with the f capital api is capital next you need to create a instance of this fast api so app is equal to the fast api and we need to use this
parenthesis we are calling it next we need to create a simple function a python function here so def you can name it anything i'm going to
name it index and it's very important to return something i'm going to return hey okay so when you have done these three steps
then you need to start the server obviously we will get error because we have not used this first api till now we have just created the instance so
let's open that terminal where we have this virtual environment then you will say uv icon then main colon app
hyphen heaven reload and this is actually given in the documentation once you have done with all this code you need to run the server uv icon main
colon app reload okay so let's hit enter so it has created the server at localhost 8000.
let's go to the localhost 8000 i'm going to hit it and let's open like here local host colon 8000
and you can see we are getting this error detail not found okay why we are getting this error it says there is no path available
how we can define that this function actually going to handle the path here comes the fast api we need to decorate with the
add the rate app and this is the first api you can see we have created the instance app then we can say dot and then we need the
get path so this is going to be the slash slash means the base url like localhost 8000.
so once we have done with this now you can see server has reloaded because we have used the unicorn main app reload flag so that's
why it's reloaded automatically when we change the file let's go reload this page and yes you can see we have this hey amazingly great so easy
this is the way we create the api oh my god just four things import instance function decorate done fourth thing and
you are done with the api this is the simplest thing you can do for any kind of framework this is very very nice next you can see i am actually returning
a simple string generally in an api and nowadays you want to have the json so simply you can use this
dictionary kind of thing returning a dictionary which says data is going to have another dictionary which is going to have name which is
going to have the value of sarthak wow we are using dictionary and when we go on the browser
reload the page and you can see we have the json returned and this is by the way i have installed the json formatter chrome extension so generally you will see this kind of
structure but since this is extension is installed we have this very nice formatting okay so we have the data and then we have a name sarthak amazingly great this is the
simplest thing you can do ever on any framework cool what if you want to have a route which says obviously not just the base url you also
want to say slash about so maybe this is going to give me the about page if i try to visit this it says detail
not found this is the by default error from the fast api but i want to create it so i will create another function and i want to name it let's say about obviously
and then i'm going to return obviously one more time data and this is a formatting system you can have
and about page what have very nice name but to make this as a real path i need to use the decorator of app dot
get because browser from the browser we are giving the get thing get to method maybe slash about once i done with this i save this file
and you can see that server is automatically restarted if i now go rear the page you can see we are having data inside the data we are having this
uh you can say list of the string which actually i don't want i want to have just the string so inside the data
i just want the string cool so far we can create a route or path for the first api and how actually we need to start the server but
let's now break it down step by step and see what is happening inside this fast api but before that you can see on the source tab here
which is not there because we have not initialized a git repository here so let's go on the terminal and i say get init once i did that it has initialized
empty git repository but next you will see we have a lot of file inside the gate that is because we have this environment directory and the caching directory both tracked by git
i don't want that so i will say dot get ignore first i'm going to add the cache file or cache you can say
directory and only to underscore then i want to add fast api hyphen end the environment directory
also we need one more thing to add which is this one dot ds underscore store yeah once i save this
get ignore file you will see we don't have extra files we just have the files we need so finally git
add all then we need to say git commit with a message of fast let's create fast api let's
uh learn fast api then just hit enter with this quotes and that's done cool
so now to understand how fast api is working first we need to go here in the main dot py which is obviously open from the fast api
we are importing fasd with the f capital api as a capital this is very important okay then we are creating the instance of this app
so this app is actually very important actually the name is very important why because if you go on the terminal and if you want to start the server what you do
you will say uv icon and then you say main but why main because the file name is main it's a main.5 module
python module then colon we define the fast api app or instance we have created so the instance is app that's why we say app
and since we also want to reload then we say reload but if you don't want that's up to you hit enter it has created the server and if you go
reload the page yes it is working but what if i'm going to change the name from this app i'm going to change to my app
now since the the uv icon work like this first you say uv icon then the module
which is main this one but instead of app now we have created the fast api instance as a my app so here we need to save
my app like this and then hit enter and again you can see server is running and it's very very nice so you
have seen that it's it doesn't matter what you name it it totally depend upon how you name and the same thing comes here
so now you can see when i use main my app it says attribute my app not found okay so we can move it to app and that's how it is working
so now let's start the server with the reload command reload and it has started that means it's going to keep tracking the changes as soon as i save this file you can see
it has restarted the server now similar to the name we have given as a app same it doesn't matter
what name you give for this function here i have given index you can give like abc yeah just save this file there's no issue
and you can see even if i refresh this is working fine same for any any function you have so now i say x y z
and it should work it is for the about okay let's try that about and yep about is also working what if i say same name to the these two
functions so abc and abc server is not not complaining what about this reload oh my god this
is the same it's working so from here i can assume or i can pretend that okay this function totally doesn't matter
what matter is the decorator here we have a app and then we have a get because we want the get request and the path we want
next i told you that the uv icon actually work very simply uv icon and then you define the module which is the main
we have given the name of the file as main what if we change the name so let's change the name to bitfumes okay so now instead of saying
main app i would say bitfumes colon app and since we have given the name app inside the file as an instance of the fast api so app
and then reload hit enter and yes it is also working so you saw that this is absolutely amazing because
everything is configurable it's not like you have to use main you have to use the app you have to use certain name for the function very flexible so that's why it is very
nice and let's get back to the mean and next thing we need to see is this names we have for the fast api
specifically this thing in other app or framework maybe you call it route sometime you call endpoints here in fast api they call it
path so these are the path this is the base path this is the about path okay then we have this thing like get we can also create the post
method then we have a put method delete method and here actually we call them the operation operation on the path so this is the
path and this get is a operation then the function above which we are defining the operation and the path using the app
decorator is called path operation function because this is the operation we are going to perform
on this path with this operation and this decorator is actually called path operation decorator so once again i'm going to repeat it the
function is called path operation function this is simply the path this is simply the operation and
this decorator is part operation decorator so path operation decorator operation path and the path operation function
it's not necessary to remember these things but it will be good if you know the terminology of certain framework what they call it will be
easy when you are going to read the documentation so now let's move into the learning of first api on the base path we just have the name
and the sarthak but instead of this let's create a blog system so i want to fetch all blocks so i'm going to use the index
and it's again you can use any name and here i want to fetch all the blocks so here comes the blocks list so i just
going to have blog list obviously we are not going to have any database connection we are not storing it we will do that later but for now it's very easy
so we are having this log list cool now next task is to fetch a single block so how we generally fetch single block so suppose we have a
path like localhost 8000 slash blog and then slash the number or the id of the blog so if i go it says detail not found so let's say
i want to show a blog and this means i want the path should be like slash blog slash id
of the block and then this id is going to have here but for now we can see we are not having any variable called
id and we want this to be dynamic like if i say one here so that one should come here so if i reload this
you can see one is there so in fast api whenever you need to have dynamic routing then you just use these
parentheses these curly braces inside you need to define the name you want to give you can give any name i want to have
id you can like say blog underscore id but id is fine for me and then you can
use that variable inside the return or you can do something like fetch blog with id is equal to the id
but before doing or before using the variable we actually need to accept that variable inside of the function and we use the same name so id comes here
that is accepted by the function or you can say path operation function but short form is function and then you can use that id here
that's great and now if i reload yes you can see it's 1 but if i say 100 now it has hundred this is amazingly
true why because we can create any kind of routing so suppose i just want to not just have the route i also want to create one more routing and that will be like
app dot get for the blog with some id but i want to show the comments
okay in that case let's define comments and here i need the id and then obviously
fetch comments of blog with id is equal to id we will do that later but return and
here i can use a dictionary of the data and i can say like comments comments is
having some other comments so there should be something inside that okay so i did something wrong it should be like
uh okay so we don't want that so commit one is like this and then comment two is like this cool so this is done and if i go reload the
page and slash blog hundred slash comments and hit enter you can see now we have a data of two comments
two and one so this is the simplest route we can create with the parameter so this is important that this parameter name or the variable name you have defined here
should be same inside the function and you have to use that inside the function and you can do anything with it now let's go
to the browser and go to the blog slash hundred here you can see yes i want this id and id is a number and
here this id is actually is a string i want the number i don't want the string so what's the issue issue is we need to provide the
type of the parameter we need so since from the browser obviously we will get the string as a default one but here
i want to say that this id whenever this function is going to accept this id i want that to be only number
so for that i can use int i'm defining the type this is defining the type for the parameter so here we have defined the id should be int
and now let's go reload this page and yes you can see this id is now not a string it's a number
but since we only accept id as a number what if we provide id something as a string so i say
my first block if i do this and hit enter you can see we have a very nice error message it says
where we have a path id we have some message value is not a valid integer that's exactly we have given here we already want
integer int and the type is type error of integer and you have seen one thing that when i have used hundred previously if i am
not defining this int then it was string so basically we get the string from the url and it's all done by the fast api to
convert that string into the integer we don't have to worry about the type conversion and that's how we get this number or integer
you can define it as a string also so if i say str string then what's going to happen since as i told you from the url we always going to have
the string so even if i have typed 100 as a number but we got string so we are not going to have any issue here now let's get back with
int and here in this routes we have created all the paths we have created let's create another path and this path is going to have the app.get
for the blog with not the id i want the unpublished blog so unpublished
okay so i want the list of all the unpublished blog so it's very easy on
published published and here i just need to return the data which is going to have
all unpublished blocks okay so that's easy isn't it but let's try it so i want
blog slash unpublished why we are getting this error see it says value is not a valid integer but
this error is for the show method or the path of block slash id why it is not reaching this one
so see what's happening fast api read the files line by line so first it says okay let's match this path with the requested path
requested path is blog and some text which is unpublished then it says okay let's match this one it says blog and then something and that something is
matched unpublished is there but then it will go into the show method it says unpublished is not an integer so i'm going to give error
so that's why it is giving error so this is the reason because the fast api reading file one by one line by line actually so that's why it's never going to reach
this one since we have a dynamic routing after block so if we want to have this walking we need to move this one especially
above this dynamic routing so now it says okay this part okay no this is not matching what about this block slash unpublished
yeah it is matching so then when this is going to match we will going to have see this all unpublished block
but on the same thing we say block slash let's say some number we will get the number because in that case blog and number blog end
6757 is not going to match with this path so it says okay i will try the next one then it will try this one blog and then something okay 6 7 5 7 is a number
integer cool return this one so whenever you create dynamic routing you have to take care about these kind of route which matches the dynamic routing and
then you have to move these type of route above all the dynamic not exactly all but the same kind of dynamic route above
so you have seen that we are having this type system and the data conversion all these things are done with the
use of pydantic so this spidentic is a library which is going to hold all the data validation is performed under hood by pedentic
so this identic is amazingly great you can see all these things are there that means we can not only just use a string and integer we can also
use like we can use the float we can use boolean and many other complex data types we will talk about them
later you know creating api is tough because sometimes you don't have any front end or
any way you can test your api but fast api is really amazing because it has a great feature of providing the automatic documentation
with swagger ui so what is it and how it's going to work let's see so yes we have all these things and the server is running i believe
yeah it's running and now let's go here on the local 8000 slash docs and if you
hit this route you will going to have this swagger api swagger ui actually here we will have all the api routes we
have created so you can see we have a index we have a unpublished show and comment same thing is here
so unpublished index and comments and isn't it cool if we can check something from here yes
so suppose i want to check that what if i pass some string instead of number here so currently i want to try it out so instead of
number i want to say i am going to pass sartre let's execute this one so now as soon as i hit execute you can see it is complaining that hey need the integer
instead of string so here we have it is saying required but if i say one two three and then hit execute it's executed no error you can check
the curl command it has done for hitting that route with the accept type of application json it has requested url this one
everything is cleaned and easy we get the response of data with one two three you can actually copy this thing and there's some just like you can paste
it obviously somewhere anywhere and you can obviously download it but you can check the response header content length is 12 type is application json when it has
executed and server a uv icon so uh this is how actually you can try it out and you can obviously clear it so that it's done and you can cancel to close this
out click here and once again you can check another route just like we did for the previous one click execute everything is once again there
with the response and super clean so when this is useful suppose you are working in a team you are creating the api and someone is creating the front end or maybe mobile application
then that person is just going to open the server docs and every api routes is available here so good this is really really the best
part of the fast api one more thing is there it's not just giving you the swagger ui but it also give you the alternative
api documentation called redoc so how we open redoc just like we did for the the docs the swagger docks now we need
to say localhost 8000 slash let's open in a new tab slash re-dock and when we hit that yep you can see we have that one
and you can download the open api specification from here it says fast api version 0.1.0 and the routes is given on the left side
this is unsuccessful show command powered by redoc and that's really great and amazing so this is how actually you perform the validation or
checking and looking on all the api or simply the documentation of all the api you have created
using the fast api isn't it very very great and this is the feature actually everyone is going to love here we are fetching all the blogs i'm
going to convert this to slash blog to get all the blog but if you try to get all the blog from your database it's it is super inefficient why
suppose you have a thousand and ten thousands of blog in your database then if you're trying to fetch all the ten thousand at a time obviously that is super inefficient
you have to limit or maybe you just want the published blog not all the blocks so what we can do we can simply provide the query parameter
here i can say i only want the limit to be 10 and i want published to be true then here i
only get uh only get maybe i can use this to have the comment i only get 10 published
blocks okay so how we can do these things like handling the query parameters so we don't want to hard code these things so let's go and first you can see the
server is running and go to the local host 8000 and by the way query parameter uh things are given in the documentation and you can check and query parameters
are like question mark then neem and equal to with the value so we are not having any base route but we can go to slash block okay so we
are getting the block list now i want to get limit to 10 and now if i hit enter it's not changing anything because query
parameter are not going to change your query so what we can do we can actually accept the query parameter just like we accept
the path parameter so this id is actually a path parameter and we we are accepting that path parameter
in the function so same thing we can do yes we don't see that query parameter but we know if we get the limit parameter
then we can use that so i can use the f string so f and here i can say limit so blog list
of or i can say blog list i can use it like this 10 blogs from the
database okay this is the new one cool reload and you can see now it says 10 blocks from the db this means if i change it to
50 the query parameter i change it to 50 it should say 50 which is here this is amazingly great because now we can have
this parameter changing the real query which we are getting it from here i told you we also want some published blog
in that case we need to provide second one with the and sign so here i can say and then published is equal to
true obviously we are not accepting the published so let's accept it here we just need to give comma and then published cool so since we are
getting this published let's use it somewhere so i can say if the published is true because we are passing either true or false if it is true then
return like 10 published blog i can say published blog and
else i can say return all the blocks written simply 10 blocks from the database cool so reload and it says true
return 50 published block what if i say publish to false let's try it uh it still says published because
this time actually we have to compare it as a true or false so what if i just try to get what is the value we are getting here on
the published so you can see we are getting as a string this is we this is not we want we want either true or false
that means we need the validation yes you can do the validation on the query parameters also so i just need to say this is going to be the bull
yeah super easy so now reload and yes you can see this is actually false that means boolean and if i return
or actually go back to the true part it's true as a boolean this also means that if i return it
yep 50 publish block but if i use the false and reload you can see now it's not saying the publish because this published is actually a boolean
and it's checking the boolean thing and returning the next string which is getting the 50 blocks it doesn't matter published or not this is amazingly great but one more
time what if i'm not providing the publish so yes since we need this published so that we can use this if else
so we need to provide it and that's how it says yes this parameter is actually required and when you are not providing anything then it's obviously
required so that means if i remove the limit part also then also it says hey limit is also required
but limit let's say i want to make this limit as a default one so default to 10 if nobody is giving any value then it should be
10. so let's make it
10. so let's make it is equal to 10. if i do this it says hey you also need the publish to be some default value so yes it is a
bool and it need the default value as true so we have defined the default value for both of these parameters that means if i
reload this page you can see yep it is saying 10 published block because we have given the published as true
but as i said i don't want let's say sort this is a sorting like sorting from a latest first so if this is the one this is not affecting we are not using
so anywhere so sort could be optional so if i accept the third parameter which is for the query parameter of sorting now it says hey you
need to define some some default value for the sort but i really don't want i don't care if there is a sorting or not
in that case you already know that if we need something to be a optional thing then what we do we simply use the optional so to define the optional field
we just need to say optional and then we need to define the the the type of this
and type should be uh string so str and since this is going to be the optional we can provide it the
default value as none yes this is great and now if i reload this page it's not saying any error and yes we have the
header because we have to import this optional so optional actually be imported from the typing system okay so i need to say
from typing import optional once i did that reload yes you can see there is no issue but
what if i'm not providing anything and i'm saying it's just an optional obviously this is going to break since we can see the vs code is also giving the same thing so
this is how you accept the query parameter you define the type of the query parameter you can provide
the default value and you can make some like query parameter as optional now let's go to another route or another path maybe this
one the comments we can do the same thing with the comments but how fast api know that if this is a query parameter or a path parameter
so suppose i want uh to limit the comment to 10 so i just say 10 but this could be treated as a path parameter
no fast api enough fast api is smart enough to identify that if there is anything given in the path and that is accepted here so this this could
be the path parameter otherwise you are talking about obviously the query parameter so in that case we can say
yeah this is 2 and what else we can say for now we can just say limit and nothing came into my mind so i just
do this so i need the blog slash 10 then comments and 10 is there so this is very silly but we are getting the 10 comments when we
are going to do the when we will do the real database part now so far we have talked about how you can use the get method only
but we also have various other methods like post delete put so generally we use post to create something so let's now
use the post method to create a new blog and see how we deal with that so anywhere we can put our
at app dot post this time you can see the vs code is suggesting us and then this should be on the slash blog that's very nice and creating a
method let's say create a blog and then i simply say like let's say i'm having a string
called data and then here i say message called blog is created
cool but then how we can actually test this post method because from the browser you cannot send a post method but remember
fast api gives you the documentation the swagger docs so we can say localist 8000 slash docs when you do that
you can see we have a new path defined as a post so we have the post method and let's click on this one now it says all the information about
this post method but we can have it try out we can have the tryout and if we execute it yeah we have this it says blog is created
amazing so this is working fine but obviously when you want to create a blog you need to send the new blog information how
we can send the information here because when we clear it and try to execute it says nothing something is given there no parameters
so let's see on the documentation what it says okay so i'm on the tutorial guide and request body so here on the request body documentation you see that it says
when you need to send the data from the client let's say browser to your api then you send it as a request body but how you can define the request body
so to declare the request body we need to use the pendant pedentic models and how we do that first we need to import the base model
so that whenever we create a class and we extend this base model then we are saying to this class hey this class is now a model
a pedentic model then we simply define the parameters we need and finally we need to declare it as a
request body okay if this is seems confusing let's do in reality cool so here i'm going to create anywhere actually
later we will extract these things to a dedicated file but for now we are doing everything here i simply say class and with the capital b i call it block because this should be
the model and then i want to extend this class with base model but this base model should be from the
pedentic so i can simply say from pidentic by dante
import base model okay that's done so after this what we have to do we just need to use this
blog the model block and then here i can let's say i just say pass okay here i need to define that the request body
is called blog and which is a type of the blog model you can call it request also like
this that's totally fine so if we do this so yes we have not defined anything here but let's but let's see what our swagger
documentation says about this reload and now when we do that it's having a new thing called request body which is required and it says there is some schema
obviously schema is empty there is nothing here and example value is not there so yes it is not
having anything what if i try to return the request from here now reload this page once again and this time i want to try it out
so let's try out execute it and it return nothing because obviously we have not send anything so let's clear
this one and let me just zoom out and cancel it then let's go and define some fields for the block obviously blog has
the title title is going to be the string cool that's great then we need the
the blog body maybe maybe this could be the text field and how we said that these things are going
to be the text or the string next this should have the blog body that also has to be string
then what we need we need the published so published at this is actually going to be the optional field because when we are creating
we we don't want to always send the published ad field and this could be let's say uh not published at it's simply published and the type is
a bull not blue it's bull okay so when we define the fields here then we go to the swagger documentation
and reload cool you can see we are having the values we are having the schema schema says it the blog need three things title body and
published and make sure this is having this asterisk this means these two fields are required
and this published is not required okay so let's try it out so we say try it out and we say string no not a string my first
blog cool now i want to execute it and since we are returning the same request we are having here this request you can see now i can
actually say uh blog is created with i can use the f string with then i can say request
dot title with title as this one so one more time i'm going to execute the same thing and this time it says blog is created with the title
as my first blog cool and this as i told you you can call it blog you can call it request you can call it anything but generally from the documentation they
call it a block okay so block.title
and execute it's going to have the same result because it is the same thing so this is how we actually create the model this is the model the blog
model then we use that blog model here and we get the values from
the user to the api so far we have seen various things but how we can debug our fast api application
it's super easy suppose i want to see what are the parameters or what are the things i have on this blog so blog
is a request body this one actually so how we can debug our application so the point where you want to check the status of your application at that moment only
you just need to go on the left most part and we have this red dot everywhere you move your cursor we have red dot just click on that red dot it become
the visible red obviously that was dull and now it is clear so this is actually the break point this means whenever you try to debug your application
then at this breakpoint your application will will going to stop and you will get all the information about your application
at that particular moment only so yes we have defined the breakpoint then what next next you just need to press command shift and t if you are on mac or if you are on
windows you need to press ctrl shift and p and then simply say debug when you do this
and you just need to say click actually and then choose the framework which is our fast api so launch and debug a fast api wearable click application
this is by default you get from the vs code so yes click here and now you can see we are having this uh error which says actually application
shutdown because localhost 8000 is already in use so i can stop the server i already have
then try to debug once again restart first api application and this time you can see i'm going to have
the localhost 8000 it's exactly same thing so yes it is working the swagger api is there tryout is there but
let's try to execute this once we click on the execute you can see it's loading loading and we are moved here on our application
and in this application you can see this one is this red dot is now having some kind of arrow and it actually describing that hey
we are stopped at this point or not actually stopped we are actually paused at this point
then you can go to the debug part here this one is debug part and if you hover over it it's a command ctrl shift and d
for me if you can see you can say debug bar or debug what's that actually um defect debug
debug debug that's where we can find it yeah this one hit view show and run debug so this one so this is exactly the show and
run debug so here we have stopped our application or actually paused our application and we can see all the local variables we have we have passed
the body the string and published because it is true by default since the default value of bool is true in python so it is true
now you can change it to obviously false if you need then that's okay but we also have other fields and other things related to python and
fast api specifically so this is the amazing thing to debug your application then you can move forward so suppose i don't want to have the breakpoint here i want to have the
breakpoint here so moving the breakpoint restart the debugging and then you can see we have all these things related to at
that moment we have options we have a name of options optional actually then we have the fast api application everything is given there
the function variables which is index show unpublished comment all these things special variables everything is given there so this is how actually you debug your
application using the fast api but if you want to change the port also suppose you don't want to have the localhost 8000
then you can change the port obviously and to do that thing you just need to say here at the bottom of the main dot py and just check if underscore underscore
or dunder name is equal to once again mean if this is true then i can say
uv icon and i need to import it so import uv icon uv i
gone like this okay and then i say uv icon dot run obviously running then i want to run it on
localhost but before i need to provide app and then comes the host and host is actually 127.0.0.1
and then comes the port and port is i want 9000. in that case let's stop this debugging i instead of using
that where is that what's the issue okay that's actually is equal to and that's done and i can simply use python
3 main dot py and that is all going to work on localhost 9000 you can see and if i go localhost
9000 that's working amazingly fine you can use obviously uv icon so uv icon
i can use the up key where is that yeah this one so this is still using the localhost 8000 but for using the localhost 9000 you can
directly use the python3 and mm.py
this is obviously for debugging purpose and you don't want to do this so i'm going to comment this let's move forward in the journey of fast api
now it's time to go into the deep and start doing some crud operation using the fast api how we can do this yes on the documentation if you go on
this tutorial guide here if you scroll down you will find sql relational databases
first it says fast api doesn't require you to use a sql or a relational database but you can use it then you can use
using this sql alchemy thing what is this this is actually a python sql toolkit and orm or object relational
mapper we will see what is this orm later and we also going to look into the references also how we can create this this file or this
documentation is very very easy but it is bit long and it take time to execute all these things like creating these files and then see what happening
but instead i'm going to explain you everything step by step so first let's start creating the groud operation for a blog
how we can do that yes i don't have anything this main dot py file is okay but i want to create a new directory called block inside this
i'm going to first say this is a python module for that i need underscore underscore init one more time underscore underscore and then py
that's done as an empty file no no need to do anything so this is done but since i have removed the environment file
i want the new thing which is called requirements dot txt mints okay here i'm going to say i need
the fast api then i need uv icon and that's cool how we can execute this one i need to say pip
3 then install then hyphen r requirements dot txt and before that actually i am going to create the virtual
environment so pip 3 and then i need not pip 3 python 3
by 10 3 and i need v e and v and yes i call it blog env
so yeah it says you have created one that's cool no issues on that so it's creating and that's done actually next i need to
go inside of this so i'm going to copy this one so that i don't have to write it okay one more time i'm going to create a yes and the
vs code is helpful and it detect that there's a virtual environment let's go inside it so it says vnv v blog env
cool now let's install every other thing we need on this what is this virtual environment and then i'm going to upgrade the pip also while this is upgrading let's
create the main dot py file inside this block so mean dot py uh what happened
main dot p y and as we know in this main dot py what we have to do say from fast api
import fast api not dislike api and then app is equal to fast api execute it finally
app dot and we want the crud operation so we start with a creating a blog so to create a block we need to use the post request
on slash blog then create a function called create and then i'm just going to return creating
okay let's say yes that's cool and finally everything is done so what we can do next we can start the server so once this is done
yeah which is actually done we can say uv icon main colon app have an fn reload but remember
this main will execute this outer or root main dot py i want the main dot py inside the block so what i can do i can say
block dot mean app and now it is done that means if i go to the local host eight thousand slash blog you can see it says
and this is not a get method this is a post method so there comes the swagger documentation or here we have the blog
post request let's open and try it out click on execute it says creating very nice but since it says there is no parameter then what we have to do we have to
provide some parameters here we can say i need title and i need the body so after that i can say title is going to be the title which we are
getting then body will going to be the body after doing that if we execute it once again
and one more time if we have to refresh yes now we can see we have these two fields then we need to say try out and say my
title my blog body execute it and yes we are getting back all these things that's one more time
interesting but you know we never want to do these things directly this is like we need the pedentic thing pedentic model actually so let's create a class
called blog we already know these things that's why i'm doing it first and i need to define and since we are we are going to create a pedentic model
we need the colon to define the type and body is also going to be the string let's use it here and i want to say this is going to be
the request as a type of blog so we need to use the colon and then i return request if i open it the server it server is
complaining and it says hey you have created this blog and you are saying that request is a type of pedentic type or pedentic field actually
which is a blog but this blog is not a pedentic thing what you are doing so we need to extend the pedentic
model so one more time from pidentic then tick import base
model and let's extend this blog class with a base model that's done and now no error here this means one more time if i reload instead of getting a simple
fields we are now having this request body and this is really amazing because now i can say
my title my blog body execute it and yes we are getting the exact same thing but this is very nice because this is a
request body from the pedentic model that's amazingly great now we need to store all these information we
got from the request body into the database for that we need to first connect to the database let's see how actually we can connect
our first api with the sqlite database but before i want to do one thing what is like how about creating a new file called
schemas dot py inside the blog directory and then move this class this schema here also we need to say
the pyramic model import comes here that's done and this means i can say from dot that means from the same directory import
me the schemas and that's cool and now it says the blog is not defined obviously because now i say schemas
dot block and yeah it's working again fine there is no error so reload and try out execute
working cool let's create the database connection so to create the database connection one more time let's go to the documentation of
fast api and get at the top first it says this fast api need the sql alchemy so if you go to the sql
alchemy documentation go to the library reference for version 1.3 or whatever version you are using sql
orm and now what is orm let's get back here and now it says the orm thing is like object relational mapping
so what is object relational mapping it's actually going to map your object into the database field and what is that actually
suppose you have a pets table then you create a class called pet and this class is responsible for the table or the crud part of this table
so simply we are mapping our sql alchemy actually mapping this pet class this object with the relation the database
so this is very very simple thing next how we can create the database connection yes it is given here so all these codes are here but the same
is actually given in the sql alchemy if you go on the object relational tutorial you can check first what we have to do we have to create
the engine so it uses n-memory sqlite database and we need the create engine from sql alchemy let's start this first i'm going to
create the database file so database dot py and here what we have to do
from sql alchemy import create engine so import create engine that's done then we need to create the engine so copy this
and paste it here but this is actually not in memory it's going to be here so i'm going to say blog.db this is the one
the database i have created so i say dot and slash blog dot db it's not now it's not
in a memory it's here but what fast api says that hey let's create a variable called or constant actually called sql
database database url is equal to this one and like this and then use it here so sql
gaming database that should be once again data base yeah but next we need one more thing
and that we can see it's given here echo as true but fast api uses connection arguments as false check
some thread false this thing okay so this is also done okay so this is also done what next go to the sql alchemy
after creating this engine next we need to declare a mapping so we need one more time from sql alchemy extend
declarative declarative base and then we need the base so copy this paste it and finally we say
base is equal to declarative base like this cool that's done after that
what we have to do it's given here like at the bottom somewhere yeah session we need to lastly create
the session from sql orm import session maker so session maker then how about creating the session so
session local the name i want to give as a session local then it says session maker here first we need to say i'm binding this
engine which i have created then i also need to give some other parameters which is not given here but we can get it from
the as fast api documentation auto commit auto flush to false paste it so that's done our database connection is set up
yeah first if so when you are first doing this it is very very overwhelming but i can bet you this is not a rocket science so you can see
we are doing all these things importing all these three things same here then we are defining the database url same here
then we are creating where is that then we are creating the engine and defining these fields so creating the engine then we define the
session local session maker so session maker is there using that we have created the session local and finally declarative base
okay so yes i have explained you how you have created this database connection but how to use this database connection and
where we are going to use it that's an another question now we have the database connection we have the database and how we can check that is there any
table inside the database or not yes we have created this table this database we know there's nothing but let's go here on the table plus this is a very nice software you can install it
for any platform windows mac linux and just click on create new connection go to the purple one which is sqlite and name it anything you want
i want to name it fast api then locate the database path which is inside my fast api tutorial blog
and actually blog.db click on test everything is fine save it double click yeah so now there is no table inside this database
how we can create the table first when we want to create the table we need to know what are the fields they're having or is there any id is there any column so everything we
have to define that's why one more time let's go to the sql alchemy documentation and you can see when we have created the base then it
says that hey next you need to create the schema for your table and this is actually the
schema but they call it model okay so here we need to create the user model which is going to define all the fields and the table name also
how we can do that in fast api in the fast api you can see somewhere we have creating model creating model creating model yeah this one so this is a creating model thing and it
is exactly same thing here here because there both are using sql alchemy now how we create it let's go and inside the block
directory create a models dot py file inside that create a class called blog
and remember here we need to extend this model with a base and this is base from the database connection
so that means we need to say here we have a base and i say from database import base and then
i can say this class is actually need the title field which is going to be a column and one more time everything is imported from sql alchemy so i can directly copy these things
because we need everything okay so column is there inside the column i need to define that hey it is an integer and this id is actually a
primary key so it's true and it also be indexable so index is true
next i need the title which is also a column but this is a column of a string next we need the body one more time a column
of string that's done it is very simple yes so we have created this model okay how we can use this model so one more time
go to the sql alchemy and finally it's given everything that's cool next where we have so we need to find a
little bit actually we need to create this database so which is i cannot find it here
no issues we can go here and on the main dot py file where i can find it here you can see it says models
dot base metadata create all this line is extremely important because it says that this line is going to create the table in your database
so here there is no table go to the main dot py and here finally i need the models and from
where i can get from dot import models or i can directly say import models
next models dot base dot meta data dot create underscore all and inside we need to provide the engine the database
engine so here i can say i need the database or instead of this i can say from
database import import engine okay so let's provide the engine
and is it good yes it is absolutely fine so we have done with this and let's see is there any error yes we have the error now finally it says you don't have the
sql alchemy no issues because we have requirements.txt file and we can add it here then we can simply say what say
pip 3 install install our requirements.txt and this is going to install the sql
alchemy for us once we done with that we can do one thing like we can save any file so that server is restarted
or reloading now it says no module because i need to say dot database and one more time i think here here also dot database
and next you can see it has actually executed this file but then it says hey you don't have the table name here so let's define the
table name also which is my table blogs cool one more time reload and it's started application started no error this means
you can see reload this page and yes we have the table into the database cool this is a little overwhelming so i'm going to recap all these things what
i have done so first i have created a database database with all these things first defining the path creating the engine then creating the session local and
creating the base then i have created the model in this model actually we are defining every field we have
to be inside the table so one model connected to a table and this table is blocks then i defined that i need the title body
and obviously the id auto incremented thing and this blog is actually a extended base of the database once we have
defined the model then we need to go to the main dot py and whenever we are running the server we are going to create all the models
into the database that means we are creating or we can simply say migrating all the tables and this is happening every time that means if the table is there it's not going to do anything
but if table is not there it's going to create it isn't it amazing this is now time to get back to our post request
and here we can actually store the blog information into our database okay to have the database here or the instance of the database here
what we need as a second argument we say db but if you return the db and go on the server server is not
complaining because it could be the name of your parameter and reload the page it's actually treating it as a query
or the query parameter but we don't want it to be query parameter so i'm going to say this is going to be the type of session session from
sql alchemy and from sql alchemy and i can actually go to the database to
find it reload yeah import session okay so we have defined it as a session
but then the server is complaining that hey this session you have defined as a type of the db is not
a pedentic thing but first it says cannot import from sql algorithm because sqlreamy.org
even after that it get an error and it says session is not a pyrentic thing so what we have to do we have to say the default value is going to
depends on a db so get db a function we have to create but before that we need to import the depends and this is from the fast api
this is going to say that this is actually going to convert the session into a patented thing but then we need the get db
connection or first say get db function inside i'm going to say db is equal to session can say session
local and remember this session is local is from the database so we can say comma database from the database
import engine and session local and then we can simply say try trying the yield the python yield part
okay yield db and then i finally say i want to close the db so if everything is done
then close the db or database connection that's finally done no error is there that means if i refresh you can see it's not recognizing db as a
query parameter but still it's giving it okay so if i execute it we are not getting anything because we are just returning the db next what we have to do actually
we have to create new underscore block and this new block is going to be the schema we have to use the model and we already
have the models so we can say models dot blog so we are saying this is going to have the title field
coming from the request dot title then we need the body field coming from the request dot body okay then
we need to say dv dot add adding new blog then when we have successfully done with the adding then we say commit then execute it actually and
finally we say db.refresh with the new blog so that we can easily return the newly created blog
that's easy and that's it so now one more time reload this page and trying out click on try out
i say title and then my blog body click on execute and yes you can see
not only we are just getting the title and the body we are also getting the id from the database this means if we go on the database reload this you can see we have one
database blog entry wow this is super so using the fast api we have created this thing and this is really really amazing so
what we did we did very simple thing first we defined the db and db should be the instance or type of
session but session is a sql orm part so we need to say the default value depends upon the dv so once we do this we get the db
instance so yes we say okay the new model or new blog is going to be the blog model
the model actually refers to the the database structure we have created or table structure we have created then we say title is this requested one
body is requested one then adding it then committing then refresh so that we can return the newly created one that's that's really really amazing thing
let's move forward now since we have successfully created the blog it's time to actually get the or get all the blocks from the database
so app.get
so app.get and slash block then defining a function so def and i can
say get or all blog whatever you want to say then this is going to return all the blocks from the database how we can get that
so once we need all these things to get the database instance here cool then first we need to say
blogs is equal to db dot query and querying on model so model dot block
and this one but next how we can move ahead how we can say i want all the blocks it's very easy dot all
yes it is very very easy then just return the blog we get from the query this is actually going to create or execute a sql query and then we will
get the blocks reload this swagger documentation and you can see now we have slash blog for the all and
it's a get request so when we try it out when we execute it you can see we have a list of the blocks so we have one blog in the database so
we are getting only one what about creating another one so let's create and i can say blog
number two and blog to body execute it yes second blog is also created
that means if i can go to the get execute it one more time yes we are getting two blocks wow amazing amazing amazing
this is very easy so with this easiness let's do one more thing what is that we can say what about getting a particular block
with the id and we know we can pass parameter something like this and say def show showing a sing simple or single blog
it get the id but we need the database instance so getting the db next we need to say the blog
which we get from the db db dot one more time query query on the models dot block but then we need where condition
but with this sql alchemy we don't have the where condition so what we have go to the documentation of sql alchemy and here it says common
filter operation so how about this query dot filter and filtering model dot the field name
with a value got it let's try i want to say filter models dot blog dot id should be equal to the
requested id but i don't want all because it's always going to give at least one or none
so i need the first this is amazing call which is first that means only giving me the first uh result yeah
so let's return blog and try it out go reload and we have to block with the id of one
and two let's try this for the get request of blog slash id try it out and id should be one
click on execute yes we are getting the first block see this one what about if i say it is a two execute second
but what if i say three we know third blog is not available execute it says none yes this is good but we can return
it in a different way so let's talk about the response code and how we can respond with the different situations
now see this thing we have two blocks in our database so if i execute yes we are having two blocks and we are getting 200 response
that's very nice but what if we try to create a new block so let's try it out and i say block three so title
three and then comes block three execute it that's great we have created the new block but still the response code is 200 actually
when we create something the response code should be 201 that's the original response code for created thing so let's see how we can add
the real response code once again go to the first api and here on the tutorial guide we can see we have a response status code this one
and here it's very very easy what you have to do on the parameter you have defined you can see it says on the decorator part actually you need to say
the status underscore code and the real code that's great so let's go to the main dot py and whenever we are creating so we have a create
a post request in this i can say comma and you can see lots of things are there but we need the status code so status code
that's great and it should be 201 so that's very nice let's once again go and try to create fourth one so fourth one
title four block four execute it and this time you can see it has two zero one response code that's an
amazing thing we have done but how do you know that what are the code for which response type generally you can
see all the codes on this maybe is it yeah here we have a python documentation for http status code and here we can see
201 exactly is created 2 0 is ok so there is no hard and fast rule yes you can return 200 for the created one
but this is the recommended thing so we should go with the recommended thing but instead uh suppose i don't know what it will be the created code or
maybe i forgot it how do i remember do we need to look into the python every time no fast api is smart enough to give us
all the codes in a very nice auto completion so what we can do here we can import the status from the fast api and then
use it how let's see so let's go here and first from the fast api i want to import status cool
now go wherever you want to return or provide the status code instead of the number itself just say status and once you
hit dot yep all the lists are there and you even don't have to read them just continue i want for the created one and boom
autocomplete is there and it has done our task so you can see this is now 201 created let's try once again and checking the
blog five click on execute and boom 201 so it was amazingly creative so this is how we can actually
return the status code for for our responses but still we are facing some issues so see
here we have the getting of the block so let's get a new block so we know the latest blog is with id of five
okay let's try to get the fifth one try it out fifth execute here yes we are getting the fifth one that's because
that fifth id is available what about 40 and we know that 4-0 the id is not available but still it's returning 200
and it's returning null this is not a good response we should we should give a proper response code plus a proper message
so first let's see how we can give a proper response code once again go to the fast api and here at the bottom of this response
status code which we have already seen you can see advanced user guide for the status quo you can click here
and here you can see when you want to return by custom when you want to written custom status code you can do like this response then
status code and whatever status code you want to give it doesn't matter what you provide here if you do this part then the default one will not be
executed but the custom one custom status code will be executed so for this thing first we need to
import the response from the fast api one more time let's see how we can do this thing okay so here we are and first as i told you
i need the response from the fast api then at the bottom we have this blog id getting the id
and here generally i provide the status code status code that should maybe um here yeah so
status code will be 200 okay so yeah that's good and it's it was by default 200 but then
i want to say if not blog that means there is no blog then i simply want to say response but i need to add this response also so
response is the type of response we get from the first api response dot status code
is equal to now since we have the status we can use it dot and not found so not found see
i don't have to remember anything hit enter and that's cool but let's now execute it so execute and it says okay 404 that means
not found this is really really great thing but for there we can also provide
the details and not details just a detail maybe and it's like blog uh blog with the id
and whatever the id so i can use the f string for python is not available
and like this cool so if there is no block we are going to return it otherwise we are returning the block
okay one more time execute it and now with the 404 we are getting a very nice response and response says block with the id of 40 is not available
what if i try to execute for the fourth id that means id4 yep we are getting the exact block with the status code of 200 which is we
want but uh one more time see we are doing these two things and fast api says okay i know that you will going to do these
things so i'm going to have one thing for you so for that uh you can search here http
response response what is that http status no response no okay that's not there so maybe i can go to the sql database
and here at the bottom or i can just search for http exception oh that was exception so here you can see when you want to raise new exception it
says http exception and this http exception should be imported once again from the fast api lots of things we are importing from the fast api
then provide the status and provide the detail in one line okay so let's try this out instead of these two things i want to
raise http exception so first i can import it http exception
and then i can say http exception inside this i want the status code which again i'm going to use a status dot
not found cool and then i need the second parameter as detail and i can copy this detail from
here and pass it okay that's done and that's done means we can see here execute yes block 4 is available
but blog 44 obviously not available with a proper detail exactly like previous one with a 404 response code
okay so that was really really great and how we can respond with a status code when you create an api it's absolutely important to provide
a better status code so that the consumer of your api or the developer who is using your api we're going to get the exact idea what this response is
and now let's work on the delete and the update of block so it's very easy now we have this create
method and after that we can say app dot delete ah so delete is a http method
to perform the delete part so we say blog but we need to delete a particular block so we need the id of the block to recognize it but what should be the status code yeah
since we know we need to provide the status code so we can say status dot when we delete something we are not returning anything so
it will be like no content so no content yeah 204 okay that's cool i didn't know that now create a new function called
uh destroy and here uh first i need the request or maybe just i need id actually no not request then i need the db connection so i can copy
from there paste it here next we need to find a block so let's find the block so block
is equal to models not models db dot query query for the model dot blog and then
i want to filter filtering from the models dot blog dot id
is equal to the given id and then give me the first one okay once we have this then we need to delete it
but how do we delete anything from the database using this sql alchemy thing whenever whenever you feel these kind of questions then you should go to the documentation
so sql alchemy go to the documentation on the library reference version 1.3 then you can directly search here i want to
delete something so search it here and i want the query api this one see query api now it says the
query delete okay so let's go here and it's very easy you just need to query then filter and instead of getting the first one
i want delete and with some synchronized session okay so that's uh something we need we don't have to care about for now we will later see this thing
otherwise you can read the exact options for the synchronized sessions but for now we are going to use the same thing false so let's copy this
and instead of getting the first one i want to actually delete the block so i just say dot delete and the code i have just copied so delete and
synchronize once we done with everything then just say return like here and return done or maybe
we can say response done or status done whatever you want to call so it's done for now so here we are on the swagger
reload we have destroy try it out and i want to delete the fifth one so click on execute and response is two zero four no content and that's how we are getting nothing
because it it's four it is two zero four this means if i try to get the block with the id of 5 it should not available so just return but it is
available why because remember whenever you do something on the db then you actually need to commit the
changes so i just actually we don't need this blog and why we have this no issues
db dot commit and once we commit this then we will going to have that delete perfectly fine so once again with the five
id execute it it says done and now if we try to get the fifth block you can see it says blog with the idea of five
is not available so this is the delete part or how we can delete the content if you want you can actually return something
like the blog is deleted successfully this kind of message but that's totally up to you so this is a very nice way to delete okay so that's
nice but still the update part is remaining and now after the delete part we need to update the block how we can update one
more time we need to create another parameter so dot this time i'm going to use put method and put on a
blog slash id and here i want the status code should be once again accepted so status
dot accept it to zero to that's good definition or the function method or whatever you want to call so it is
good and we need the id then we need this time the response so ris or request actually not the response okay so this response should be the
schema dot blog and then finally we need the database so we can copy and paste it
and here for now i'm just going to pass so see this request is a schema.blog and this is the same thing we did here on the create remember
this request means whatever we pass from the browser or from the swagger so once again refresh this page and now we have this
orange one which is put for update of the block click here and here we are having this schema this is coming because of
the where is that where is that yeah here because of this request if i remove it and now if i refresh this page you will see that yeah we don't have the
schema so that's why we need the request body or the which is going to be the schema of block okay so we get it one more time how do
we update it this is a question the answer is on the documentation of the sql alchemy one more time i need the
search bar and on this i'm going to search update and i need the query api query api is here click on this update and this time you
can see it is here it says you just need to query on a model then you need to filter get that one and update with the fields you want one more
time you can use the synchronized session or you can use evaluate you can read about that how they are doing or what are these things but what we need to remember here that this
method is a bulk operation so suppose you have a user with the email uh two user with the same email suppose and you are updating so that's going to update on
both of the user so this is a bulk update okay so that's cool just like with a delete we don't need to get the like a first or all we don't have to do that thing
finding like filtering and then directly update it let's try it so since we have it
so i say db dot query query on model dot blog
dot filter filtering models dot blog one more time but blog.id
should be equal to the id and after this i need to update it but what i have to update first i need to pass the title and it's
it's a dictionary the title should be updated title like this okay but then we need the synchronize
what's that synchronize session i think yeah so uh yeah let's see what what's going to happen if we are not doing these things so one more time i just need to
return uh maybe you can return the blog or you can return the request so i just returned that
updated successfully like this so let's try this thing so reload and now we have a schema this time i want to update for the fourth block
and this time i say update it and that doesn't matter because we are not using it currently so click on execute and it says updated that means if i try the
fourth one try it out fourth execute and it's not updated so remember one thing we need to use the
db commit so db dot commit and that's good
one more time let's go on the put providing the ideas for and title is good click on execute it says updated now go
to the get a particular blog providing the ideas for click on execute and this time it is updated title but what we need we need to update with
the text we are getting from here since we are passing the dictionary from here or it's like a json so it's going to pass it and we can
directly pass the request body so we are passing full request here that's me that
totally mean that i can say updated title again and body also updated
click on execute it says updated that means this time if i get the block with the id of 4 click on execute yes
title is updated and the body is updated so both are so both are successfully updated that's really great thing
so this update part is fine but one more time what if we try to update a blog which is not available inside the database
let's try to execute it it says updated 202 obviously this is incorrect so first we need to check if blog is there if there is a block then update otherwise raise the
exception so i'm going to cut the update query and first i say block is this one i'm not doing dot first because we don't
need it when we update so that's how it's just a block then we say if not block dot
first then i need to raise http exception and here i can say status code is a status dot not found
and obviously the detail is like using f string block with id off this id
not found and if this blog is available then we can simply say blog.update if this is good
blog.update if this is good then we will see the error so here we have a 34 click on execute 34 is not available inside our database
this means we get 404 not found blocked with the id 34 not found cool one more time if we try to update fourth again and again
like this click on execute and it says update it that means it should updated the fourth with a updated title again and again so let's try
yep it is nice we can do the same thing on the delete part so we can grab all these things
and go to the delete part and first i say like what happened so first i say like this
and then i say block and i should cut it and paste it like this so first we are having the query of blog then we are checking
if block is not available then raise the exception if block is available then delete it commit that transaction or the database query and then return the response
same we are doing an update first we are preparing the query then we are saying okay give me the first one that means if there is a block give me it
if that is not available raise exception if blog is available then update it and then commit the transaction and finally return the response that's cool
and this is how we do the full crud part in fast api isn't it amazing in a short span of time we have seen how we can
connect database and create all the great part with a valid response code and a very nice messages lot of things are still remaining in
fast api so let's learn about them and now let's work on the response model what it is let's go to this first api documentation and here we have this tutorial guide
once again here you can see we have a response model and a response model as the name suggests for the response we are going to define some model how we
can do that it's super easy response underscore model and then the model name and by the way
since we are calling it on this decorator and this is going to be the pythag model and in
fast api we call pedentic model not as model we call it as a schema remember we have created various schemas not various
only one and this schema we call is a pedentic model so because we have two type of model one is pedentic model and one is
sql alchemy model which we really call model so for the sql alchemy model we call it model as the name suggest but
for the pidentic model we call it schemas so here when we say response model that means a response schema okay so don't be confused with the response
schema so response schema means response model so how we are going to use it and what's the
use of it see here we are on the documentation and see we have this show blog show let's try it out and i want
to get first block if i execute it yes i am getting the blog with the blog body title and the id suppose i don't want to show the id
how i can hide it or simply i can say i just want to show body and title in that case we need to create a model and that model is going to be
identic model this means we are going to create a schema we already have a schema for the blog let's create another schema and i call it
show block you can call it anything and then i'm going to extend not the base model i'm going to extend the simple blog this one
and here let's say pass because i want title and the body and these two things are given there so we don't have to do anything since we are extending we already get these two
fields now we need to go to the main dot py for the blog and wherever we are getting the blog with id we need to
define response model so response underscore model is going to be remember this is going to be the bidentic model
and in fast api my identity model are called schemas so we are already importing the schemas so here we are from the dot
means the same directory import schema that means we can say schema dot this time i want show block okay so that's done
if i save this file go to the server everything is fine now let's try to execute it that means getting the blog with the id of one if i click on execute
we get internal server error why we are getting this let's go here it says valet value is not a valid dictionary
so we are doing something wrong and to solve this let's go to the pydentic documentation this is the real pidentic documentation
and here i'm going to search for orm and yeah this one i think so is it good no i i think this
is not the one i want some different one um maybe i can search for config yeah ora mode this one i need so we need
to actually define the orm mode when we define our model so how we define whenever we say there is a model this type of model and then we need to create a config
class inside the model class and then we just say orm mode true why because we are using this
db query that means we are using the orm sql algorim so we need to define it that hey we need to use
the config with this capital c because it's a class and here i need to say orm mode
is equal to true when we do this let's try to click on execute to get the blog with the id of one and now you can see we are just getting
title and body so let's do something and here uh instead of extending this model i'm going to extend the
base model and here i'm going to actually write i need only title this is a strange but let's try this so one more time i'm going to execute it and yeah
we are just getting the title why because we have defined the response what type of response we need we need a response which is exactly similar to the schema
we have defined or the pidentic model we have defined here this is really really amazing now since we are also have one route or one
path which is getting all the blocks from the database here we are so let's go close this one and there we have all click on try out
execute one more time we are getting id for each of the block we don't want that one more time we need the response body
on this decorator we say comma response model is equal to schema dot show block
is it going to work let's try this i'm going to once again click execute get the internal server error why
it's not acting as a like a response model it's saying field required value what what it is i didn't get that because
we are having not one blog we are getting the collection of blog so actually we need to say here
i want a list of this kind of schema so i just say i need a list but this list is a type and we need to import it from the typing
so from typing import list once we do that here we are where is that yeah so once we define that
the response is going to be the list of show block then if i execute we just get the title for every block we have in the database that's not good
so i just want the body also as str and execute to get title in the body for each of the blog
so this is very very amazing and you can read more about this in the documentation tutorial user guide response model and everything is given here so that's
pretty amazing thing and now let's move to the next important topic whenever we create any application we always need a
user in our application so let's create a user using the post request just like we did for block let's open the block directory
and we have a mean dot py here i will go at the bottom and here i say app dot post on a slash user and
create a function called create user and here we need just i'm going to pass it but here we need
the request and request is going to be um how this request is going to be so we have this post request for blog yeah
so here we say schema dot blog similarly we need schema dot user so first we need to create a new schema for the user
so yeah that's that's good we have the schemas dot py and here i'm going to create class called
user which is going to extend the base model of pydentic remember the schema in fast api is a pythentic model
so here we need to define what we need we need the name of the user that is going to be the string then we need the email of the user that is also going to be the string next
we need the password and that's also going to be the string that's great now let's use it so i say schema dot
user simple and for now i'm going to return request and see what we are getting so when i reload this
swagger api and here we have at the last user and this user need three things email password and name so if i
execute it yes we are getting it back but as we know we need to store in the database so we need the database connection so i can copy it from anywhere
so copy that and i'm going to paste it here then how i can create it one more time
whenever we create we need the sql alchemy model that's very important thing so see we are doing this same on the blog models.blog
models.blog where we actually define the table structure so let's have a look on the models.py file
models.py file here we are defining one for the blog let's create one for the user class user going to extend the base the
database base and then here i need to define the table name is going to be the users
and then what we need we need the id yeah so i can copy that exactly same then as we have already given we need a name
which is going to be a column of string then we need the email one more time column of string and finally password column of string so we have defined this
that's great now let's use this model the sql alchemy model very important to distinguish by identic model we call it schema and
sql alchemy model as model so here when we are creating the user we are having the request schema dot user and then we have the db connection then
we first need to say new user is equal to models dot user
and here we need to provide the request and this is going to create our user but then we need to say db dot
add new user not block new user then db dot commit and finally db dot
refresh so that we can return the new user like here is it good let's check on the blog part
so we have defined manually okay that's that's not a issue so i think this is going to work so what i'm going to do i'm going to
first open my database connection so that i can see i don't have oh i already have because i ran one time so we have the
user so why we have that because on the main dot py we are saying that whenever we find any model let's create it on the
database so models.base.metadata create all
so models.base.metadata create all that's why we have this but we don't have any user inside that so one more time here we have the post
request for create user try it out and i say name is going to be sarthak and then sarthak
at bitfumes.com password is password okay let's execute it and we have internal server error let's see so
server error says hmm uh models.user uh
uh models.user uh not found i think okay no issues
we have the user models dot user is it good yeah we are having it
maybe let's try this name is equal to request dot name then
email is equal to request dot email and password is equal to request dot password one more time
let's try click on execute it's giving error refresh okay so we need to say refresh on what refresh on new
user that's how it's going to create it and yeah you can see now we have this name id email and password so that's two times because
previously we had the issue for the refresh database but it was committed so we have the new user so we have two user i'm going to delete
both of these users and then i'm going to create one more that is going to be the only one okay so we have the user but you can see that
password is exactly the same it's not hashed it's not encrypted so let's work on encryption of the password
when we create the user the password is not hashed not encrypted let's go to the fast api documentation and here i'm going to search for hashing
so it's already given as a suggestion click here and we get this page here it says password hashing and it's recommending
us to use passlib library uh python library to create hashing of the password how we create it let's see here it says first you need to import the
crypt context then you need to create an context password context by defining the schema you are going to use and some deprecated auto and that's
again not a big deal then using the password context you can say password context dot hash the password okay let's try this
first we need to import this or we need to install it password lib so i'm going to add it on the requirements password lib
then i say pip 3 install requirements so passlip is installed then
what next here this is going to be super big the main dot py later we are going to refactor it but from pass lib
import crypt context is it correct we're going to actually copy it from oh so we need to say
from passlip.context
from passlip.context import the script context then i'm going to say here pwd underscore
context or cxt is equal to crypt context and then here is it in the
yeah it's simple schema and auto deprecated that's done next when we create the user just before that
i need to say like hashed password and like this is equal to password context dot
hash for the request dot password like this and now instead of passing the request password
i'm going to say hash to password okay that's nice and now we have a password so i'm going to
delete this one and now i don't have any user in our database let's one more execute it and it's having some error okay no
issues let's see it says big crypt no back end available recommend install one like pip install big crypt okay it says you don't have that schema
so let's install it so one more time open the requirements add it run the pip 3 installation
and that's done when it is done let's see there's no user one more time click on execute
yeah we have the encrypted password amazingly great you can see this password is encrypted wow we have done that on the database
yes it is encrypted cool so this is how you can actually create the encrypted password or you can say the create user with the password encrypted
so what if you don't want to do something like this so what you can do you can create a library or not library you can create a simple class that's going to help you to
create things so i create a file called hashing.py and here i'm going to create a class and class
called hash and inside i'm going to create a function called hash dot let's say encrypt or maybe be crypt
because we are using the big crypt okay so bcrypt and this need the password so this need a password which is going to be the
string so that's a pedentic thing and then we can use this only all these things we can cut paste it here
and then we return hashed password or if you don't want to do this you can say inline everything so we need the password context so this means we can move this part
password context here and then we need the crypt context so we can cut from here and paste it here
like this so everything is good and we don't need request and it's simple password um
everything is fine let's try this okay so now i can directly say here
i need hashed password but here i can say using the hash and we need to import it
dot and first let's import it so from dot actually where we have the dot and then we say hash okay
this hashing actually hashing okay and from the hashing
hashing dot and we have the hash class hashing that dot dot big crypt and we can provide the request
dot password one more time let's try this with another user our user will be like search 2
and execute it and yes we can see we are getting the sarc2 as the user and this one is encrypted we can make it
more generic like not hashing hashing lots of thing we can simply import like from
hashing import hash that's going to be better one and then we can totally remove this and this is going to work let me try one
more time so three three execute it and taking time white is loading loading loading
is there any issue yeah no module called hashing okay there is no module called hashing why is that because we need to say dot hashing
okay that's done and now you can see third one is also created once once i completed that four four execute it
and that's done boom now what if we want to get the user but we don't want the password you know what we have to do we have to create the request model
whenever we create the user we don't want the id and password to be returned we only want the name and email and you know what we have to do create the user response model that
means the schema remember when i say response model that is not related to database that means i'm talking about the pidentic and when we talk about the pedentic we
are talking about the schema so we have this user but we don't want this password so we can say show user is going to the base model
and it just need name and email okay that's cool so we have this user when we create the user we say request
model and model is it model or models models no oh that's response model that's simple error
response model is going to be schemas dot show user that's cool one more time
and i'm going to create the fifth user user 5 user 5 execute it and internal server error you know why remember one thing
this config so copy that config paste it that's cool one more time let's try to execute yep we have the name and the email
similarly let's create another route or under the path to get the user getting with the id obviously
so at last yeah i know i'm going to refactor this main dot py file later but for now i just want to get the user
with the user id okay and we know the response model is going to be like this okay next get
user and this get user need id which is going to be the ain't actually not a string then we need the db connection and
db connection is here finally we need to say like return i'm not returning here i say user is equal to db dot
query and query on models dot user with the capital u dot filter and i'm going to filter on models
dot user dot id has to be equal to the given id dot first now
if we have the user or i can say if we don't have the user if not user then we can return response and we can copy like here
and something like this and now i can say user with the id of something something not found cool everything is good then return
user okay let's try reload this page and this time we should have some error that's why it's not loading and now it says
okay so i think i am doing something wrong here what happened it says invalid syntax invalid syntax because i need the colon
here cool and one more time it's not going to be the triple equal to yeah double equal to sometimes javascript comes in my mind
okay so one more time here we can see try it out and i want the user with the idf2 execute we have the user with the proper response body
cool now what if i want to get the 22 user oh this user is not available in our database that's great that's amazing amazing one more
problem we can see on this documentation is like every route whether it is related to blog or it is related to the user is available here and all the blog is actually called
default one now let's see how we can show the routes or these endpoints in a proper manner using the tags
let's see how tags are going to help us in defining these routes in a proper way inside the swagger documentation it's just for the documentation so it's
not going to affect our code or the structure of the code and how we are saving and doing things so here on the tutorial part we can see
we have the metadata somewhere we need to find it yeah metadata and docs url okay so here one very nice thing we have which is called
use of tags here click on that and this one yeah so how we can add the tag so it's very very simple wherever you are defining the path you
just need to say tags and defining the tag name how it's going to help let's see so we have various path or routes available here how we can
define one so anywhere you can simply say comma text and in a array or simply list you can define it
like this is for the block or maybe blocks okay i can copy it because i need it for
various slots so comma blocks and comma what is happening comma blocks and one more for
comma blocks and last one blocks and this is for user we will see it later so once again if i refreshed
here you can see now we have a separated routes which is saying for the blocks we can unwrap it or wrap it so this is very very cool because we don't have to look we
okay where does our user are okay here it is no you just need to check okay i just want the user route so just like we did for the block cloud we need
for the user route so we have this user out say comma and this is going to be the users one more comma users
super easy yeah so now we have two section one for blog one for user when we are going to test the blocks we can unwrap it and do something here and wrap it
like this when we are going to work on users that's amazingly easy so this is this is a great thing which uh fast api provides for the
documentation overview and making the documentation easy to read also you can see we have the various schemas for here that is again not just because of tag
but it's because we have the fast api we have the blogs isn't it like
every blog should belongs to a user so how we create a relationship kind of things or we need a foreign key inside the blogs so that when we fetch the blog we also
fetch the owner of the blog or maybe the user who has created or when we create or when we get the user
we should also fetch the related blocks or created blocks that's how comes the relationship in fast api here we go on the fast api and search
for relationship uh how spell relationships like this and we have this one
sql relationships and here when we want to create a relationship we need to import the relationship from sql alchemy.orm if this is from the sql
sql alchemy.orm if this is from the sql alchemy that means we can go to the documentation of sql alchemy and search for
relationships and if we search it we get various results but we are interested in the sql alchemy orm relationship let's click here
and we get the relationship api how we create a relationship it's very easy when you define the sql alchemy model
you mean to say like the table structure simply then you need to define the relationship something like this but before that you also need to define
the foreign key so one more time we can search for the foreign key so if i search for the foreign key there is a
schema foreign key available and here at the top let's go yep so here we can define our where is that
yeah we need to use the foreign key and define which foreign key from which table we are going to use and actually everything is given
in the documentation of as fast api so let's copy this line from here and now open the models here we have the model for the blog
let's paste it and now i want to define one relationship how this relationship is going to be it's like
not the item maybe in the item so say we have a blog blog has the owner with the relationship we need to define the model
then we back populate means the reverse thing what is the reverse thing and we will see this what is reverse thing mean okay so we define it like this
owner or maybe i call it creator instead of owner create create you are is it correct
yeah this comes so creator relationship on users and back populate as blogs okay
this means the back populates means i need the relationship here also that i call it blocks which is going to be the relationship
on the blog model and then i back populate this one to the creator i think now you got the point here is the creator back populate
the reverse one and on the creator back populate his blog yeah but since we are using this relationship we need one more column in the block table which is called
maybe user underscore id this is going to be the column of integer and not with a single quote simple integer but then we also need the
foreign key so i can copy it from here like this foreign key and foreign key is going to be the users
dot id so this is the user's table and then id since we are having this foreign key we need to import it
from the sql alchemy that's done okay so this is how we define the relationship is it going to work i don't know let's try
so how about getting on here reload this page and what if i create a new new
block then what if i say with relationship body is abcd anything
and execute it it says internal server error maybe this is for the blog user underscore id and that's true now to solve this thing what i'm going
to do i'm going to actually empty out all the tables so now we don't have any table this means if i now reload this page
or the server actually then it's going to create the table for us and this time you can see now we have the user underscore id and user underscore id if
you go on the structure yes is an integer and here we have given the user underscore id as a foreign key and that's how it is a foreign key okay
so that's great one more time if i click on execute with the block details so
block with relationship and body is simply body and execute it yep you can see now we have these things
but we have issue and it says user underscore id is null we don't want that so if you go here it's having null
we don't want that so what we can do we can open the main.py for the blog and when we are creating the blog then
we are passing title and the body and for now i'm hard coding user underscore id as one so one more time i'm deleting the
database and let's hit execute once again and this time yep we have the user underscore id that's amazing and we have achieved this
with the help of creating and adding another column that's good but still what we need so since we have a block with the id of
one let's try to get that block so we have a show and now try out click on one
and click on execute we have the id we have the title and the body we also need the creator this thing
okay and how we transform the output the response body yes with the response model so if i go on the get
part of the blog we have this get blog we say this is a all blog for a particular blog we say here schemas dot show block that means we
need to go into the schemas and on the show blog i also want to load the relationship how we do that for this we just need to
say here creator but creator should be the type of user or instead i can say show user so this is only going to have the name
and the email because we don't want to show the password of the user okay so let's get it here and i say this is going to be the show user
but then it says okay so i think i removed the str now it says show user is not defined but we already have it so actually what is happening it's
reading line by line so when when python goes till this point it says okay show user is not available so let's move this show blog
below show user okay now you can see we don't have any error cool so let's go here and click on
execute still one more error and this time it says none is not allow value actually we don't have any user in our database so let's first create a user
then we can assign that blog for that user so create a user and name is sarthak
okay we have to try it out so sarthak then sarthak at bitfumes.com and password is password okay that's done
execute it so yep we have the user now i can close it and then create new blog with all these things
and actually i should reload this and then i create
blog with relationship and let's try to execute it and this time we are having this block
okay that's good and now we can show the block block 2 i want to show so try it out block 2 click on
execute and this time you can see we are having the title body and creator which is holding name and email amazing this is
really really amazing so with that why not let's have the user with all the blogs so here i have get user and we only have one user
so we should get two blocks because we have defined two blocks but we have to define it here how we can define whenever we show the user
so here we have the show user then we can actually say i need blog but that block should be the list of so first we need
to import the typing list from the typing so typing import list and then comes here
list of the show block but if you do this once again it says hey you don't have the show blog because show blog is after this
also we don't want every time to load the creator when we when we load the block for the user so what we can do we can find this block
so we can say it's just going to be the list of blog okay one more time try to execute internal server error
it says field required actually we can refer to the documentation and in the documentation it says list of item and i think that should be
defaulted to like this is it good i think the point is it should be blogs because the relationship we have created
and yeah this is actually blogs cool now let's try this execute still we have the
problem so what if i just say this is going to be a list simple list now if i try yeah it is working but we are getting everything from the block table we don't
want that so why we are having issue when we are using block as the identic model or the schema
so see in this blog we are defining title and body but we don't have this config oram mode to true as soon as i
do that that means i put this here and now you see if i execute it you can see we have the blog
title and body only so this is very important to have the config so what i can do actually instead of having the
config here i call this as a blog base maybe then i can create one more called blog which is going to extend
blog base and since this is extending i just need to define that this is going to be the orm true here okay so this means
now everything will work super fine so let's try one more execute it yes it is working so this is the very simple way
we can have the relationship from user to blog from blog to user our application is now growing so it's time for the refactor and managing this app
as a bigger app that's why when you go on the fast api on the tutorial user guide at the bottom here you can see bigger application multiple
files let's click here and first thing i can notice here is that yes we have a main.p by but we have a very important folder called routers or routers or routers whatever
you want to call so since we have two different kind of routes one is for block one is for users let's see how we can extract on
different different files first we need to create a directory and create init dot py file so that python recognize this as a module
let's go here and inside this block because we are working for this blog and i'm going to create routers and inside that i'm going to create
init.py
init.py file okay so that should be file not a directory so that's done simple
but then i need the let's say users users not users just user.py
okay so we have created for the user one is also for the blog blog.py we have two different
blog.py we have two different route files how we can put the route in it let's go and let's see how we have yep we have this one import
the api router so let's go here so here it says when you create the and the file
actually this is where that let me see it like yeah so this one is for items okay so when you have created a dedicated file
then you need to import the api router from the fast api just like we import the fast api then we create a app instance just like that we need to create a
router instance let's see how we can do that so from inside this block.py i say from fast api
import and importing api router that's good then i say router is equal to api router and initialize this one then
i can put one by one every route here inside the block dot py file so for that i'll go on the main dot py and first thing
i want to get is for getting all the blocks so where is that get and here we have so get blog so i'm going to copy it
then comment it here maybe we need it later and i will paste it here but instead of this app.get i'm going to say router.get
app.get i'm going to say router.get
and everything else is going to be almost same yes next what we have to do we need lots of other things like we need the schema
okay that's not a problem so i say from but now i need to go one directory up so i say double dot and from double dot
import schema okay so that's done but we also need the list from the typing so from typing import
list and then tag is done then we have a db okay so we need the get db in our main.py file
what we are doing we are having this function here so isn't it like we can move this function into the database directory or the database file
database file we have created so here we have a database dot py at the bottom i'm going to paste it okay so session local is already there we are just getting it
yield database and finally closing it so we can get db we can get this getdb function from the database cool so let's go to the blog.py the
router file then i i say double dot actually there is the double dot and then i want the database finally i want to
say this is going to be the database dot get db okay that's once again done one more thing is models we need models
so one more time we need the models okay so we are getting everything running here so finally let's go on the swagger
reload it and we are having some issue let's open it and it says get db is not defined okay what we have done we have removed the get db from this main dot py
so wherever we are having this get db what we can do actually for here i can say get db is equal to database dot
i think we are importing something yeah so we are importing from the database engine and local so session local we don't need now so we just need getdb so now everywhere
we need the getdb like here here everywhere we have it done is there anything no and now if i refresh
you can see we don't have that get blog or getting the blog like this one all this we don't have why because now we need to register this route
on our main dot py file so we have this main dot py and here what we can do we can say yes we have the fast api but then we need to say app dot include
router and then define whatever the router we want to give so let's go to the main dot py after
this or anywhere actually i say app dot include router is it router routers simple router and then i need to import the router so
from router import or actually how they are doing import item end user okay so from router import block
okay and i can say blog dot router so we need to actually say block dot router because later we will have a user dot
router so that's good next reload it we have some issue i think yep and the issue is no model route okay so it's not router it's
routers and this should be from the dot routers okay so now it says depends not uh defined okay so here we have to use depends that is from the
fast api so like what i did yeah so from the fast api also import depends and session is also not there is yeah
here we are using session so this is from sql alchemy so we can cut or no not cut we need it here also and paste it is it done yep everything
is done now let's reload it and yeah we can see we have the blog all amazing let's try this and
execute it to get the blogs yes we have the blocks with the creator that's that means it's working absolutely fine now since we have moved this all block why not
move all the routes for the blocks here in the block dot py okay so i am going to remove this one
and i'm going to first try the create blog part from there i'm going to paste it here and instead of app i say router and let's see
is it anything we need yeah we need the status from the fast api so from first api we need status yeah this one and tax is good and then we have a
schema we have session depends we have getdb we have models we have and we have a new model cool i think we have done everything
correctly but getdb is not defined okay so that should be database dot get db so i can do one more thing
here also i can say get underscore db is equal to database dot get db and in that way it is always going to have that get db that's
done and yep we have the create one done so i'm going to this time cut at once all these things
like till here and paste it here so let's do one by one so for the delete i need the router and then we have i
think once again we yeah we need to use the http exception from the fast api one more time so http exception
code is done block.delete
then put comes router anything else i think no need for doing anything so remove this one and
this is also called router.get
and no need to do anything remove the commented code and is there anything yeah we need the response also actually we don't need the response we
are not using this response so i can totally remove this one like here yep everything is done
once again reload yes we have every routes working okay so that that was for the blog let's do the same thing for the
user so cut the user related things from there paste it here and let's import one by one so
from fast api import api router then we say router is equal to api router initialize it then we also need
the db so from double dot import database and i say get db is equal to database dot
get db we also need the schema and we also need the models okay so that's importing part then we have a schema and
then we we need the session also so i can copy from sql alchemy paste it that's depend depend things i can actually copy
everything from here like this then it is doing all these things hashing hash we need to import and we are importing hash here
from hashing so we can cut because now here we don't need anything and this should be from the double dot
double dot hashing import hash so i think everything is good and now we need to change this app to
router cool so we are moving very fast http exception we need i think we haven't already imported this one let's see okay there everything is good
we don't have the user routes because we need to now use this user.py into main.py
so just like we have imported blog from the router directory or the our package we also need the user similar to this
i can say user.router and now everything is fine reload swagger yep we have these two cool this is amazing amazing and now you
can see our main dot py is very very clean and we don't need uh exception kind of thing depends
no we don't need the typing i think like this no need these things and no need get db from here no need
session yes so main dot py is simple and where is model okay main dot py okay so we need the model
where is that yeah so remove it and remove this and remove this okay when
everything is fine now it's time to learn more about how this router is going to help us
minimizing the code we have written here we have done very nice refactoring all the routes is now available inside the routers directory where we have a
blog.py
blog.py and user.py every route is there
and user.py every route is there but you can see if i go to the block dot py everywhere in every route we are defining this tag
here here here here and here okay now instead of defining this tags here what we can do we can actually
define this tag inside this api router when we initialize this router and this is actually given in the documentation as you can see
here yeah so when we define the api route we can say tag and whatever that tag you want to give so now i'm going to remove all the text from
here multi-cursor remove it and this means i can verify everything is fine if i reload
you can see now it's back to default but we don't want to do that now let's say tags
is equal to inside an array we can say blocks okay so let's reload yes we have now the blocks same let's do for the user
open the users.py remove this tags here and now when we initialize this api router
we can say tags is equal to users like this you can make it capital u and capital b here that's just the name you want to give for your
documentation it's not going to affect your coding that's amazing now next refactoring we can do is called prefixing so we can prefix all the routes with some name
so since we have all the routes all the blog routes actually prefixed with blog slash block slash blog and then then do doing something so we can define here
we say prefix is equal to slash blog with a comma and now everywhere we are using slash block we can just
say slash so we can remove this thing and we just say slash an id then one more time slash id and the last
one slash id okay so this become very clean reload and yeah it's having the same thing because we have used the
prefix if i remove the prefix reload it you can see it's just the base url but that we don't want let's do the same prefixing on the user
so we need the prefix of slash user comma reload and we have a user slash user because we need to remove the user from here
user and user that's cool reload yeah we have a slash user slash user with the id
so these two things are making our code very very clean let's do one more refactoring on the routers here we have a block.py and inside this
block.py we are doing everything
block.py we are doing everything think about this what is the responsibility of router to route or to give the path
then just return something but here we are doing lots of things fetching the user adding it committing refreshing returning and lots of other things like returning some other response
isn't it good if we can extract this in a dedicated file so you can create or you can name it anything i want to name it repository so repository
directory inside this repository directory i'm going to create blog.py
this is for the repository that means we are doing something inside this okay so first we are getting all the blocks
so isn't it like we can create a simple function called get or get all and then we perform these two things so cut from
there and paste it here now we need the db so we get the db this is going to be the type of session we can import from sql
alchemy dot or m import session then we need the model also so from
one directory up import models and then all so now we can use this inside our router so first we need to import
so from and from the repository repository actually i need to move one directory up and then i say repository
repository import importing blog okay so that's done and now here i just need to say return
block dot get all it's a function now let's try this reload try and execute
server error we have done something wrong it says missing parameter so we need to pass the database so we pass the db query and not a db query just a db and yes it is
working since this is working let's do the same for everything now we need to work on the create of the block so here i can create one more function
called create i'm not giving create block because this is inside the block so it also it always mean that creating the block
so i'm going to extract everything and here i can say block dot create yeah and then
paste it here and see what we need we already have the blog model then we need the request okay so we need the request then what we
need we need the db db which is the type of session okay and then everything is fine
let's pass the request and the db and make sure this request has a type here also it's the same thing okay that's done
and try it and actually we need to return this block.create reload
block.create reload and i think this is reloading that means we have to okay schemas is not there
so we also need the schemas done so now it is refreshed and that means we can now create a new blog
try it out and execute we have the new blog in our database id3 that good and let's do for other thing then we have a delete
one so which is very long so cut and return block dot destroy maybe we can call it we need the
id and we need the database also so finally at the bottom definition of destroy and destroy
function need id which is going to be the integer and then we need the db which is going to be the session and finally destroy is this
db is there model is there filtering then http exception come from the fast api so from fast api import http exception
and status code also so we need the status from the fast api and finally it is done i think yeah that's good and now try
for the delete one and it's loading we have missed something block dot destroy it says and that should be return
spell it correctly and now it's done so let's try to delete the third one which we have just created
this execute and we have some error i think okay so what happened here response is two through four okay yeah it's working two zero four
what about thirty three three and now it says blog with the id not found this is also working final one uh not the final and which is update so
return block dot update we need id then we need the request we need the db
finally definition for update we need id as integer then request as schema dot
what's that schema.blog and
db as session it's just typing we are providing everything is good and let's work on the final part
which is db or not tb return blog dot and block dot show is it good then id
and then db and here i can also provide this as an integer and here also as a integer
here also as an integer that's good okay let's finally create for the show and we need the integer id as
integer db as session and that's good everything is done and that's great
and now see our router file is looking very nice getting returning all create create destroy destroy update update show show and every logic is now inside
our blog repository same we can do for the user which is going to be very quick because we have very less
information in our user dot py router so it's creating the user
so we can call it user repository also dot create and here we can pass the request
and db and here we have so create and we need the request this is going to be the schema.schemas dot user and db is going
schema.schemas dot user and db is going to be session paste it and now what we need we need various things
we can copy from here not here from the repository where is that yeah blog repository so maybe we need these things only
so we need the session we already have we need the schema we already have then we have a model cool then request we're getting from here then hashing
yeah we need the hash so we can go here on the router we can cut this hashing from there paste it here okay that's cool
then everything is fine finally we need to import this one so say from um how i can
do that on the blog repository we have no not on the floor yeah on the blog on the blog router we can see we are importing like this
from the repository so on the user route we can import it as user okay so
and we can call it user repository but let's call it user also so user only that's done and
router dot get so get so user dot get or maybe show yeah show is good so id and db and
finally dot show id as int db as session and paste it http exception is already
there finally everything is smooth now you can actually remove the imports we are having and we don't
need like this this actually we need the response and some of other things we can do it later okay so that's done let's try this
yep everything is working fine so that means we can create a new user try it out and string
at abc.com and that should be the abc.com password is password
and i call it name as a string execute it and response is null i think i did something wrong which is on the
user router we have to always return whatever we are returning from the repository
so this is how you create new user so one more time if i execute it yes it says these things that's great
so we can get a single user try it out with id of two yes we are having it everything is fine and let's move to the login part
now we need the user login system so let's create the route to log in the user with the email and the password we are going to use this documentation
extensively so first we need to go to the security and here we have the password and hashing bearer jwt so this one we are going to
use but first what we need the route so i will go here on the routers create a new route
called login.py
called login.py or maybe you can say authentication dot py okay here i'm going to
yes import from first api import api router create a router instance for api router
and then i say router dot this is going to be the post for slash login and then we are going to define a function called
login and here we perform the login so we say login we need to register this one on our main.py
main.py so we have this main.py
let's register login or authentication authentication dot router and i want this to be at the top it doesn't matter where you put it's just a personal
preference everything is done and server is not complaining about anything that means if i go reload this page
yep we have this one why not make it as a tag so tags is going to be authenticated
authentication correct reload oh what happened okay so that's not here so that's on the router
comes here one more time yeah that's done now since this is a post request we need two thing one is username and another is
password here we are actually getting the username but we are finding through the email so here we need the request
and request should be for a proper model so schemas sk schemas dot login and we need to create this one
go on the schema at the bottom class login and extend base model of pidentic model
and then what we need we need the user name which should be string and then we need the password which is also going to be the string okay
that's cool close this and yep we have done that so from double dot import schemas cool
let's reload this page and now if you check here it need two things username and password next we need to get the user via
email actually the username is going to be the email and why we are doing this as a username we can call it email that doesn't matter but since the uh the jwt or the password
thing uh which is oauth 2 password bearer need password form actually or 2 password request form need user name as the identifier not the
email so yes we can call it email also anyways we are going to find the user so user is equal to db.query that means
we need db yes so from everything we need the database also and now we can say we need db as
session which is going to depends on get db from the database dot get db okay so
from fast api depends okay then we need from the sql alchemy
so why it's not auto completing no issues so from any other file i can copy this and that's done okay so we are having
this that means we can say models dot user that means now we need models models dot user dot
filter models dot user dot email is equal to request dot username one more time you can call it
email but since we are going to depend upon this oauth 2 password request form we need the username first if there is no user then we are
going to return a response or maybe raise http exception so for that i can open the blog
repository and here yeah this one i need it so paste it and we need the status from
the fast api and then i can simply say credentials invalid credentials invalid
credentials at the last we are going to return the user let's try this so we are going to refresh this page
and we have some issues i think it says some bad thing and this is a really great it says if there is no user
how about repository so if there is no user raise http exception okay so http exception is not imported
one more time save it still it's giving the same error is not callable what which is not callable thing
hmm so it's not given every anything here okay so i think i got the point it says on the db get db so this is not going to be the
callable thing and yes now it is good so since we have everything try it out we need one
username is sarthak at bitfilms.com password is password execute this one and
we are not getting anything it is saying oh we need to say dot first finally one more time execute it yeah we are
having the user but now we don't need the user we actually need the access token huh this is going to be the interesting because now
we need to implement the jwt thing before that we also need to verify the password how we can verify the password so if there
is no user we are returning this exception or raising the exception one more time we need to actually check or verify the password so i say if
hash dot verify and hash dot verify that means we need to import hashing library so from hashing
so i say from dot dot hashing import hash and hash dot verify verifying the
user password which is going to be the hashed one because on the database we have this hashed password then we provide the request password
that means the password user has given if this is not verified that means the password is incorrect then we raise
same exception or we can raise different exception maybe like we can say in correct password which generally we don't want
to do but that's okay for now for this if everything is fine then what we have to do we have to here uh
generate a jwt token and return it we need to do this later but first let's go to the hashing library so not library
a file so we have a big crypt the password be creating system let's create one more called verify and first we are having the hashed
password and then plain password these two things we are getting so yeah first we have a hash password then we have a
plain password now next how we can check it so return pwd.context
dot verify and then verifying both of these things so hash password and plain password and one thing we can
verify it from here so it should be verified yeah verify password password context dot purify first we need to provide the plain
password then hashed password okay no issues so first plain password then hashed password okay so that's done
and let's try to give incorrect password so in correct password execute it it says incorrect password
if i provide the correct password we get the user okay so everything is done and next important task is to
generate jwd and return it our login function or login route actually is working absolutely fine but now what we need instead of getting the user detail we
need the jwt so here we need various things to generate the jwt first we need to install one library which
is called actually it is given at the top python juice so we need this one so let's say requirements
passion python juice then pip3 install requirements and that's quick that's done
next what we need once we have this then not the password hashing thing we need to start with these things like
uh we need the secret so that we can uh we can encode the gwt we need the algorithm to encode the gwd and the expiry time
so copy these three things and we just need them and what we can do actually we can create another file
for the jwt so maybe i can create it token dot py or you can also call it jwt token but for now token is fine for me so
i put these things here like this then what next then it says you need some models one for the token one for the token data
so let's copy these two models from here and models means the schema actually because these are pidentic model so pedentic model here means schemas on
the schema file i'm going to paste it and yes we have the username but maybe we can call it email we will check that later
so that's cool next what we need we need to create the where is that yeah this one oauth to scheme
but before that what we actually have to do we need to generate the jwt and here we have the create access token so lots of things are there i'm going to
explain it one by one so first i'm going to copy everything from there and go to the token file we have created
and just paste this it need the data which we are going to pass obviously expire delta this is going to be the expiration time
time delta is going to be the thing we have to import from date time so copy this line and from time date time import time
delta then what we need next date time datetime.now that's
datetime.now that's done and yeah then we need the jwt thing remember we have in installed the
what we have installed i forgot and we have installed python juice so from this jose i need to import
jwt error and jwt so that's how we are encoding two encode we get from this thing and
secret key which is here algorithm which is one more time here and encode jwt that's great let's see how we can use this thing
one more time it says create access token and that create access token is very simple to use how
once we have the user then it says login for access token this one so once we have the user we provide we create the time delta expiration time and then
we use this create access token we pass these things and return the token so copy these three lines from here go to the authentication
routing and here i'm going to paste it okay next we need the time delta and the minutes so see we are providing
the access time and we are providing it optional so let's now skip this one i'm not giving it so what i'm providing just using this
create access token this should be from the token so import it from double dot token import and actually we just need to
import the token so from the double dot import token and now i can say
token dot create access token this one which is providing the data as user dot user name instead of username i'm going to provide the email actually this is we are sending the data so see
what happening we are checking the user if there is no user we are saying there is problem if the password doesn't match we say okay password is not matching if everything is fine
then we say okay to create the token we are passing the user email id okay here on the create access token we are getting
this as a dictionary which is we are passing it then we need the expiration delta which we are not providing because we don't need it
since it is optional or you can totally remove this because we are having it if there is no if there is expiration time then create expire otherwise create expire as 15
minute only okay that's done and finally to encode dot update we are going to add the expiration to the data dictionary we are having and
then finally encoding this is very simple now let's see if there is error on the
yeah there is error on this server so it says the optional field is not there what i can do i can totally remove it i don't want this
so i can say like this and now i'm creating my expiration time from here and you can provide this x axis token expiry time
as like here which is for 30 minute and that's cool let's see if i save this it's reloaded one more time it says optional where is that
optional is coming from let's see it says okay so schema why in the schema
okay so we have this optional we need to import from the typing one more time reload everything is fine on the server
let's now see reload and we are having the login try it out password uh username is sarthak at
bitfumes.com password is pass word click on execute and yes congratulation you can see we are having this access token
and we can use this access token to further use but where we are going to use it we need to actually protect some of the route or maybe all the route behind
the authentication or behind the token actually so we only want to access this routes when the user is authenticated otherwise we need to say
you are not authenticated or maybe unauthenticated now the final thing remaining which is moving these routes behind the authentication
how to do that first we need to go on the security then oauth 2 with the password and jwt and we need to use this oauth 2 password bearer this is
going to be very important so first what i'm going to do i'm going to create a new file called oauth 2 dot py
and make sure you spell it correct so oauth 2 then how we can actually perform this thing so whenever we need any route to
move behind the authentication we need to say that this this route is actually going to depends upon get current active route and what is this get current active route
or active user get current active user is actually getting the current user and this is the dependency simply saying it's a simple python function
which is going to check if the token is valid or not so we are going to decode it and then we are getting or returning the user details let's see how we can implement all these
things so we have created this oauth 2 and here we are going to create the definition or actually dependency we call it get current
user this is the one and inside this we need the token and then what we need next we need the that that to be
depends upon oauth 2 scheme okay so that's cool so let's click and yeah now we need the depends so depends comes from the fast api so
fast api import depends and then we need the oauth to scheme what is this thing
so once you import this security oauth to password bearer here you need to create the oauth 2 scheme and
just defining the url and what is this we will see this later and it says where you want to fetch the token so this is going to be the
login route so this is the route or url from where the fast api will fetch the token okay so that's done
what next next it says okay so http exception so this is the exception it has created so we can create it and http exception
comes from the fast api and status code is 401 if it is there then could not provide some header so that's a very simple things but next what
important thing is we are going to try to decode the decoding the token we are having so i'm going to copy all these
till here and paste it how it is first we need the gwt but we already have the jwt in our token.py
file so it will be good what if we can create here and we say verify token
verify token and like this this function is going to help to verify the token so this means this try and error exception thing we can
move here and then we can simply say from same
from actually we can simply say import token and then we say token dot verify token okay
but let let's see what we need here so we have the jwt yes we have the jwt decode we need the token okay so that token will be something here
so we have the token that should be string i believe let's see is it yeah that should be the string and that should be depends upon this
scheme but we don't need it because these things we have done here okay so we need to pass the token here once again verify token need the algorithm
we already have the algorithm then it says from the payload get the sub if this is successful then this will be the email actually because we are
putting the email here then if there is no email raise the exception which is saying that exception
should be also here like here and we say exception which we have created here this one next we say token data which is
a token data and remember this is actually the schema we have created the token data schema very first this one okay
and this need the email maybe yeah we call it email so this should be the schemas dot token data and we
don't have the schema so from uh i actually just need to import schemas okay so we have the schema
and providing the email and the email that means key and value and if there is some error we are again raising that same exception
okay so this is very very easy and finally we can return this thing now let's try this and we are first yeah we also need to
use it on our route so current user defining the schema and then depends upon this file or this function get user so let's try this
on the blog or where is that blog router yeah so here when we fetch all the blog
we say yes this is a db session but also it need the current user which is going to be the
schema of user but that depends upon that depends upon this thing get
current user so get current user should be from our oauth 2.
so from simply import so from double dot import oauth 2 like this
and let's see what errors we are having because i know there will be lots of error first we need to import from the security
which should be here and from fast api
dot security security import oauth to password bearer and where we have used here we have used
next it says get current user is not defined i forgot to say that this is going to be the [Music]
uh oauth 2 dot get current user or 2 dot get current user and now it says schema is not found in the token dot py
so we are using this we need to we have imported that but it says its import is incorrect so we have the token so we can say
from dot import schemas yes no error that's cool now if i go reload this page wow you can see you can see this thing we have a lock
authorize and we have this lock now if we try to execute to get all the blocks try to say
we are getting not authenticated but what if i want to check it so i say authorize we are having this nice page for this
and we can say sarthak bitumes.com then password is password authorize we have some error let's see
on the network tab on the axis it says hmm so why we are having these things so whenever we want to
get something from the the token then we need to say it should be um the the data should be oauth to
password request form so that could be the reason and from the authentication authentication route
we don't want this request to be the schema login this should be this one auth 2 password form and that could be imported from
fast api dot security import oauth 2 password request form and that depends upon nothing
like this and one more time let's try this and yes you can see it is done and from the the login we are getting the
token you can see i can zoom it for you it's too big but okay so it's really too big yeah we have the token access token is there
so i can minimize it like here move it down and since we are having this thing that means yeah you can see this lock is now visible
and this means we can try to execute and we are not getting anything but still be getting error for something str on the verify token so
oauth 2 and it says str okay so this says str depends
has no attribute verify token so somewhere we oh we have some issue we are having this token and we are naming this
the data we get as a token so we can rename it to token library or maybe we can rename
this thing to and maybe data data will be good so we can say data okay one more time click on execute
still we get the token has no attribute con verify why is that so we have the token we have the verified token
and i think i get it so we say from dot import token and click on execute yep we are getting it yep
very nice and this is amazing and when we want to move every route behind the authentication what we have to do
and we can change it not to get current user what is this this should be current user only current user not get current user so
current user is a schema and depends upon the get current user and that's i can post i can add it everywhere
like this and not on that decorator sarthak this should be on the function and finally
cool so if i reload here it's going to have the problem somewhere okay so i miss it edit something wrong somewhere yeah
online number 20 20 20 is this one okay so we say db current user
and yeah we need to close this i think and then we need to close somewhere else and this one also and
we need to close this one also and one more time line number 24 i miss it
24 that's done and everywhere we have a lock lock lock lock whoa so we have done authentication everywhere
is it is amazingly great now one more time i'm going to do at last the very last thing i want to have
is open this postman to check the api so now we have this postman let's try to get localhost 8000 slash blog this is going to get all the blocks
which says not authenticated cool and i want to log in so login and method not allow yes we need the post request then it says
you need to provide the fields missing that means password and not body that should be the email okay so on the body part form data i will say
user name is equal to sarthak at bitfumes.com and the password is password send
it we get the token so copy this token on the new
route we get localhost 8000 and on the header i want to provide the authorization
bearer token send it and yes we are having that block data if i am not sending the authorization
token it says unauthenticated woohoo final application is done so it was really really nice journey on the fast api
now comes the final part of our application which is deployment yes we are going to deploy using the data or data whatever you want to call so data is a
sponsor for fast api and we need to create the account then we can get started with it so i'm going to create a simple account and then come back later
so i have created this account on the data and this is it look how when you're first logging in so how we can do that
so we have the documentation here but on the fast api also given that you need to create your application we already have you have to give the requirements.txt5 file we already have
requirements.txt5 file we already have then install the cli we need to install the cli for the data so copy this thing
and paste it here so yeah hit enter it's going to create or install the cli data cli for us
then we need to log in into our data cli so open the terminal and we can check by just typing data okay so this is completed and i say
data help and data is not there why is that okay so maybe if i restart the
environment and i think this is going to get it yes so now we have the data next what we have to do we need to log in so
data login so data login and it's waiting and then it's giving a simple ui
for login let's try this and sign in and it says working on cli and i think that's done and logging
successful okay once you done with that you say data new and successful created a new micro okay and
we need to define all these things and adding dependencies and boom that's done okay that's super super easy so let's go here so what we have to do here we just need
to say beta new and when we do this it is actually going to put all these things into the server so yes we have the git ignore for a git
thing but we don't want to put this environment file so actually this is saying on the documentation you will see that it says first you need to create a directory of
your project and then mean and requirement but we have total mess so what we can do we can create a new called
new directory called app and that should be directory or folder called app here i'm going to move this requirement
so i'm going to copy and paste it then i need this blog also copy and paste it and then
what i'm going to do i'm going to copy all this blog folder into this app so this is going to be like i
will cd into app okay so this is the app i want to upload inside we have a database we have a requirements but then
inside this blog we want to move this main dot py from there into the app okay so now we have the main dot py so since we are having this main dot py and we
have this blog as a module a python module because we have a dot underscore underscore dot init so what we can do
instead of saying dot we say blog this is the blog means from blog means from blog python module
so everywhere wherever we are using dot we need to replace it with block to have a proper path structure and then we have done with this next
uh we we need to do the same thing on everywhere wherever we are using this dot so we can use it like here on the schemas no
and here we are using tokens so blog dot token or from blog import token that's done on the models we are saying
block.database then hashing
block.database then hashing doesn't need anything from the dot neither database need anything on the router we have a users
it says from double dot means blog and we need to import all these things similarly blog dot repository because we have this block module then
repository module this is very nice and then on the blog.py
blog.py we have to import from the blog one more time blog dot repository
next next is authentication so blog dot hash these are the things we are doing here to make our
uh project structured with a proper path system and finally this one
blog dot hashing and that's done so now we can check by running our uv icon so we say first where we are
we are on the main so we need to say cd into the app and now since we are already on the environment
now we say uv icon main dot mean coolan app and reload so it says address already in use so i can kill this one
and one more time try it it has started the server let's try it reload and we have some issues it says python multipart so we need to install it
on the requirements this is going to be here see this requirement file requirement.txt inside the app we have this is for the data and for
our environment we have this requirement on the base so python multipart that's done so we need to say pip 3 install
requirement not that one we need to say we need to go on this main and then pip 3 requirements and
everything is done cd app and uv icon okay that's cool reload once again
and this is nice it is working working fine that means if i try to get a user with the id of not d with two
and yeah we are getting so everything is fine so this is working and now it's time to deploy okay so one more time remember this thing
that what i'm doing we need to be inside this app directory where we have all our blog application then we simply say
data new and hit enter so once we do this it's going to put all these things into the server and yep you can see it successfully created a new micro
new micro means if you go on the data and here we have a mac micros reload this application and we should see
yeah we have this app and this is our application and now it is deployed and adding dependencies so that means it's installing all the requirements thing we have
so that's again done so that's how we do these things and this means if you visit this url it should give us everything we need to wait
okay so it says bad gateway so we can we can go to the visitor and reload this page to see what error we are having this is error like python multi-part
okay so we have done mistake like here we have added multipart but we need to add this multipart on the app requirement also this is for
remember this requirement.txt file is for the data okay one more time this time we need to say deploy because we have already created new so
we just need to deploy the changes so this is deploying changes updating dependencies since we have installed the python multi-bot okay so every
dependencies is installed this means now one more time if i reload this so that i can clear this visitor
field or field or page or whatever it is here we are reload this and wait for it to complete yep there is no error that means i can go
to the docs and we will get the swagger api cool so that means if i get the user with the id of to execute it
and yes we are having that user wow that's great this means what if i try to authenticate this user and authenticating with the details we
are having password click on authenticate and i think we have some issue here let's see
okay that's done it was a little slow so that's done so now let's try to get the all blocks and try to execute we are executing
and we are having some issue which is unauthenticated but we are sending this token bearer token let's see and here we say
unauthenticated request header okay i think i got the point data is using uh like forwarding or reverse proxy
actually it's using reverse proxy maybe that's why it's not forwarding the authentication header and that's why it's having the issue but obviously when you
deploy this on a real application or real server not for testing purpose it's going to work fine so this is for the fast api and if you like this
please please share this video with your friends and don't forget to tag the creator of this fast
api with this tutorial and say that how awesome this tutorial is and you just need to go on twitter and go and search for this
twitter handle for tengalo and he is the creator of this fast api tag him with my twitter handle which is sarthaksavi so if you have any issue on the fast api
or if you want to learn any other thing then just comment below or you can email me message me anywhere dm me whatever you want to call so just saying thank you for
staying with me till this point and we will meet in some other videos till then goodbye
Loading video analysis...