Intro to FastAPI - The Best Way to Create APIs in Python?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in today's video i want to give you a quick introduction to fast api so fast api is a python framework that you can use to build apis obviously so the nice thing about fast api is that it supports uh asynchronous functionality and the framework itself is asynchronous so uh in a sense it's more high performance than a typical uh web framework like flask or django even though there are ways you can make those asynchronous but fast api is built to be asynchronous also the nice thing about it is you don't have to write as much code because by using the python type hint system uh fafsa api is able to figure out a lot of things that you want to do so you don't have to write the code directly another thing because of those type hints that it can do uh easy conversion to and from different forms of data so with an api you'll have like data coming through the requests so it can convert that into data models that you have in your code and then when you want to return something to the user it can convert those data models back into something that the user can actually see and then uh along with that there's also validation so because you have these type hints and because you can have some data models and use those data models as type ins fast api is able to give you some validation just based off the type ins and i'll show you how all that stuff works in the video so this is the api that we're going to build i have um swagger open and basically it just allows me to add some cities that have time zones so if i add a city like los angeles and then i have like america los angeles i can add that as a time zone and it just creates that for me and it returns the thing that i just added and then i can add another one so for this one we'll say washington dc and this will be america slash new york and i can add this and then if i go to the cities here and try it out i can get the cities that i have in my database it's just like a list in my app and it also tells me the time in those locations and you know their actual time zone you know how many hours offset from utc and also i can delete here and specify an id for a city so i want to delete the first city which is los angeles hit execute nothing appears because it's a delete and then i can go back here and query for all the cities again and we see washington dc is the only city left so that's what i'll be covering in this video and let's get into writing the code okay so to get started first we need to install the framework so pip install fast api and i already have a virtual environment open so just waiting for that and then we need a server to run our api so you can use either uv corn or hyper corn i can't get uv corn to install on my machine so i'll be using hyper corn but they do the same thing so you can pick one if you want to follow this video just choose hyper corn like i am so pip install hypercorn and i'll just wait for that and then getting started is pretty easy so i'll create a file called main.pi and in it i'll import from fast api so from uh fast api import fast api and then i need to instantiate an app object using the fast api class so this is similar to flask if you've used flask before so app equals fast api just like that and then once i have that i can start writing in points so i can have an api so the easiest one would be a git request so what i can do is i can take the app object and use a decorator so the at sign and then app dot and then you can use an http method so get posts put delete patch options and so on there are a few but you would only use maybe four or so in a real app so for this one i'll have a git request and i'll put it on the index so this is very similar to flask except instead of app.route it's app.git so this part is actually similar to bottle if you've used that so at this point i need to create a function underneath the decorator so i'll just call this index and then from here i can return some data so what i can do is i can just return uh something like a key and then value right so now to start up this app what i have to do is i have to use hypercorn so hypercorn and then i need to specify the name of the file so main and then the name of the app object inside the file which is app so a colon between the two then i'm going to use dash dash reload so the server will automatically restart every time i save the file so i'll start this and then i'll go over and open up the url in my browser so let me go to the browser and i'm going to the index and now i can see key value so it's really that simple to get a result but of course you can do that in flask or bottle and that's not really interesting so what we're going to get into next are the features that make fast api unique so first is the automatic documentation so you actually get two forms of documentation you have swagger so you just go to your url and then slash docs and you get swagger here so i have one endpoint and it's called index and i can open it up and i can see information about how it works so if i click try it out and hit execute then here i get the response which is just key value and there's also a different type of documentation called redoc and it's just a different way of displaying you know what each endpoint is and what it can do right so we'll come back to swagger uh for this video and i'll show you more how it works but just know that you have automatic documentation generated for you when you create your endpoints in your app so i'm going to create a sample api to kind of demonstrate how fast api works and what's cool about it so first i'm going to create like an in-memory database just to hold the things that i want to display from the api and things that i want to allow the user to insert so db just equals an empty list and then what i'm going to do is i'll create a few endpoints so for this i'll have four endpoints two of them will be get requests so i'll have app.git and then slash cities and then i'll have one for getting a particular city so cities and then slash and then some variable to hold the id of a city so i'll just call this city id and it's just curly brackets around the actual name of the variable that i'm going to use then i'll have one for post requests which will allow me to create a city so cities with no trillion slash and the final one will be delete which will allow me to delete any cities that i've added into the database so now i want to create the function that goes under the first one get so i'll call this git cities and what i can do here is very simple i can just return the information from the database so the easiest way to do that would just be to return db so one of the things that fast api will do for you is it will create a json version of any data that you pass as long as it's well defined so for something like a list or strings it's pretty easy to convert and as we'll see later it can also convert different data structures that you create as well let me comment these out because they're going to cause the program to crash because they don't have functions underneath them but here we see if i go to this endpoint which i won't do it's just going to return an empty json object that's not very interesting so what i want to do next is i want to allow the user to actually create a new city so before i can create a new city i have to kind of define a structure for a city in my app so to do this i can create a model for it and i'll use pedantic which will allow me to create a model and it uses the type hints that i talked about earlier to define the type of fields that are in it so i'll say from pydantic i import base model and then up here just below the database i'll create a model so i'll call this city for the model and it's going to inherit base model and then i want to specify the fields that are in city so name and time zone are going to be the two that are there and what i want to do is i want to specify the type of them so this is where the type annotation comes into play in python so instead of doing something like name equals you know feel dot string this would be like marshmallow if you've ever used that before instead of doing all that all you have to do is say stir and then for time zone i can say stir so if i had like a list i can say list if i had a dictionary i can say dictionary if i had a date time object i can say date time or so on whatever the data type is you just put it here after the colon so i have two fields in my city and they have the type of string right so now when i go to create a city so let me go over to posts so actually uh need to uncomment this one and i'll create a function underneath and i'll call this create city so create city and here is the part that is a lot different than probably any framework that you've used in python so here i'm going to use type annotations again so i'm going to have a parameter called city but in addition to the parameter i'll have a type for the parameter and it's going to be that city model that i just created up here so by doing this fast api will automatically expect something that resembles a city to be in the body of the request so when i go to swagger and create it you'll see how i can create a city in the body of the request sended and then fasta api will pick that up you know it will put it in this uh variable called city and i'll have it available as that city argument so what i can do here is uh because it is a city object what i want to do is i want to put it in my db and there are a couple ways of doing it i can put the object itself directly into the database but instead what i'll do is i'll convert it to a dictionary first and then put it in my database so to do that i just can do db append right and i'm going to put the city in there but i'm going to convert it to a dictionary so i don't necessarily need to do this but i'm going to do it anyway just to have a common structure because if you want to see this database with some things it'd be a lot easier to have like dictionaries in here first instead of creating cities but if you want to create cities directly you can uh don't think there's anything wrong with doing that and then what i want to do is i want to return the thing that i just inserted into the database so i can return the last item in the database by using negative one right so what's going to happen is the city is going to be in the body and i need to add a colon here and then i'm going to convert it to a dictionary and append it to my in-memory database and then i'm going to return it right so now let's take a look at this in swagger so i'll go over to the browser and i'll go back to docs we see a post request that's green i can click it and here there's an example request body so name and time zone and it says they both need to be strings and if i click try it out it's going to give me those two things as placeholders and then i can create a city so for instance i can say las vegas and then i can have like america los angeles for the time zone i can execute this and it looks like everything was successful i get a 200 response and we see down here i get the um same thing in return so it just mirrors uh what i insert it into the database so now if i go back to my git route where i'm just returning everything in the database and hit try it out we see i have a single thing in my response las vegas america slash los angeles so if i add another city let's say miami and i'll use america slash new york and execute everything was successful if i go back up to execute for the git requests now we see two things are in the response so i have both las vegas in miami and they're both in my in memory database so that feature of allowing type annotations to kind of tell fast api what to expect and how to handle it is what makes things so much easier because in a different framework what you have to do is you have to kind of take the model and then take the input data and use the model to interpret the input data and then create like some object in return right so you have to do a few steps you would have to create like a method in your class to convert it if you didn't have any automatic way of doing that and something like you know django rest framework but really the idea is just by using type hints fast api can figure out a lot of things that need to be done for you without you having to specify them more explicitly so now let's work on the delete one because the delete is pretty simple so i'm going to create another function and i'll call this delete city and for this one i want to have a city id so up here i'm going to do slash and then city id so in this particular case the the uh city id is going to represent the location in the list so the first id so id1 will be the thing at the zero index uh id2 will be at the first index and so on so for this one because i'm expecting a city id i put city id here as a parameter and then i need to specify a type and the city id is just going to be an integer and then what i can do is i can delete it so by deleting i simply mean popping out of my in-memory database so i can do db.pop and then city id minus one right because if it's id1 i want zero so i just have to subtract one and then i just want to return nothing so i'll just return an empty dictionary okay so let's try this again so because my app restarted i have to add things into the database again so i'll just execute that for miami and now add las vegas in here again so america los angeles it's the time zone right so now i should have two things in my in-memory database and i do so miami in las vegas now if i go down to this and let me just refresh the entire page so i can see the delete city here so it's in red and this doesn't mean it's the error just means it's delete so i can hit try it out and it's expecting an integer so if i say city id one i'm expecting that miami will be deleted because i just added miami first so execute i get nothing in return so now if i go back to cities and try it out and execute now i only have las vegas in here instead of uh having miami in there too and just to show you what happens if you try to insert something invalid in the url so if i go to cities well actually i can't show you this in the browser yet because uh it needs to be for the get request so i'll show you that momentarily what i want to show you is putting invalid data in the city id but for this one swagger won't even let me execute it because it has validation itself so on the endpoint for cities here i'll show you what happens when you do something invalid so i have app.git and then city so i want to get a particular city in the database so this is pretty simple i'll create the function and i'll call it git city and then we have the city id and once again it's going to be an integer and to do this i just simply need to return db and then city minus one so it's similar to popping we just look for the item at the particular index once you subtract one from the id so now we can go back to the app and once again i have to add the cities in so i will um let's see try it out and then i'll add las vegas and then america slash los angeles for the time zone execute that and then i'll add miami and then america slash new york is the time zone and i'll add that now if i go to get cities i still get the two but if i want to get a particular city so let me refresh so i can see the one that i just added so here this get cities slash city id and if i want to try it out and get the first city i get las vegas if i want to get the second city i get miami so now to show you what happens when you add something invalid so first this is valid so number one so that's an integer but if i try to add something that's not an integer like some random string and hit enter i get this error message that's generated for me automatically so this is another nice thing you have these error messages that are generated for you because fast api knows what to expect and if it gets something that it's not expecting then it knows the kind of error message to generate so just telling me that the city id is not a valid integer so that's a pretty good error message so if i change it back to one then i get the value that i want so for the last thing in this introduction video what i want to do is i just want to complete the api that i showed you at the beginning of the video where it handles the the actual time using the uh the api that i have here this real time api so what i'll do is i'll install requests and then with requests i'll query the api so pip install requests and then i'll just import it down here i'll need it and what i'll do is i'll go over to let's see i want to put the information in the cities here so basically what i'm going to do is i'm going to take the time zone that is stored in my in-memory database for the particular city and i'm going to get the time for it so to do that uh in cities i'll create a results list first and what i'll do is i'll loop over each city in my database so for city in db and then i'll perform a request so r equals requests.get this is going to be an f string and then i just need to get the actual endpoint so i'll just go down here and it will tell me the current time zone so i can just take let's see which one is it this one so just take this url put it in here and then the value that's going to be dynamic is going to be the actual time zone so i can say city and then i want the time zone for the city so remember city is going to be an item in my database which is a dictionary so that's why i can access it in this way so all my cities will eventually be stored in my in-memory database as dictionaries so i can access time zone like this and then i can get the result so the uh current time is going to be i think as r json so i'm converting the request result to json and then i can just get date time right and then i can append that to the results so i'll say results dot append and what i want to do is i'll just create a dictionary so uh the name will be city dot or a city name and then the time zone will be the uh city time zone and finally the current time so this should be a string current time will be the current time right and i just noticed this should be this should have double quotes so let's see yeah it just told me that so let's restart the server and let's try that again so let's just refresh this here and then perform a get request on cities and i get nothing here so let's see oh that's because i need to add data into the database so i'll go over to uh posts and i'll add one so we'll have las vegas and then we'll have america slash los angeles execute that and then i'll go back to get cities execute it i get an error probably has something to do with the api so what i'll do is i'll print out the results from the api so we'll do print r dot json just so i can see everything that i get and i'll restart the server and i'll go back and uh i'll add las vegas back in there so try it out we have las vegas time zone is america slash los angeles execute cities get city try it out execute again air and the results is it looks like the same it looks like it didn't return correctly but let me go ahead and see what it looks like when i do this so i'll just copy the link here and i'll put america slash los angeles and it says unknown location so maybe that's it let me see if i uh have the locations correct so here's just a list of all the valid values we have oh it's america underscore los angeles so let me go ahead and restart the server and try that again and i'll just add that underscore there so it hopefully works this time and i'll remove this okay so i'll start up the server and i'll go to post to create it we'll have las vegas and we'll have america slash loss underscore angelus okay so execute that and then i'll go to get cities try it out execute and i get a result here so for this one it's still not updating well and that's because i'm not returning the results i'm returning db so just one last thing i get this one working we'll go and we'll add the city again so at las vegas and then we'll get the results and now we see the current time in los angeles down there and of course if i add miami in there it will do the same thing and i could also do the same thing in the cities one if i wanted to if i wanted to add the current time i would just perform the requests basically like this so i can just copy this um but by first getting the city so city equals you know db city id minus one perform the requests convert the time to json and then basically return this so i'll just take this dictionary i'll copy it return that and then it's going to work for my endpoint where i get one particular city so let me just go ahead and do that and i'll create a city again and then i'll go to the one for getting one individual city city id one because i only have one database or one item in the database and i have las vegas and then i have the time zone and the time again so there is so much more that can be done and especially with async stuff i didn't use any async stuff in here so when you're using anything that has like a weight in it either within this function itself or somewhere down the line like a function that you call within the function just have to specify this is async but since i didn't do anything asynchronous in this example i didn't have to put it and if you put this here nothing will happen if there's nothing async but if there is something async then you have to have this uh just keep that in mind but there's so much more to cover for fast api so if you like this framework and you think it's kind of an interesting approach just let me know i can definitely make more videos about it so leave a comment down below tell me what you think about fast api and if you want to make more videos about this so that's it for this introduction if you have any questions feel free to leave a comment down below if you like this video please give me a thumbs up and if you haven't subscribed to my channel already please subscribe so thank you for watching and i will talk to you next time you
Info
Channel: Pretty Printed
Views: 106,759
Rating: undefined out of 5
Keywords: fastapi, api development, python, python web framework, create api python, tutorial
Id: kCggyi_7pHg
Channel Id: undefined
Length: 25min 47sec (1547 seconds)
Published: Fri Sep 04 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.