How to Use FastAPI: A Detailed Python Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
fast API is the blazingly fastest API framework among all the other blazingly fast API Frameworks out there it's really fast that's why it's called Fast API because it's so fast so I'm going to show you how to set up a simple API today using fast API there's a couple of really cool things that fast API does that make developing an API really easy and fast did I say it's fast before you start building a new piece of software though like an API you need to think about the design so I've written a guide to help you get started you can get this for free at Ariel note codes design guide contains the seven steps that I take whenever I design a new piece of software hopefully it helps you avoid some of the mistakes that I made in the past iron dot calls design guide have also added the link to the description of this video now if you're ready let's dive into fast API really fast in order to have a running API server with fast API you're going to need to install obviously fast API but you're also going to need a package that runs a server for you and what's often used together with fast API is uvicorn now if you do pip install fast API all this is actually going to install everything that you need fast API plus all the optional modules including uvicorn if you want a more reduced set of packages installed then you can also just install fast API but then you still need to add UV cord and then you can indicate that you want the standard UV corn package installed and then this is going to give you the basic set of packages that you'll need the example that I'll show you today is an inventory management system and here I have a very basic setup so obviously I'm using fast API here and in the first line I create an instance of fast API that's that's the app that we're going to add all the routes to then I have a couple of helper classes so I have an enumerated category of tools and consumables and I have an item and item has a name price count and ID and a category an item inherits from base model which is a class that comes from by Danzig fast API relies on pedantic for all the validation and definitions of objects I'll talk a bit more about by the antique later on and then I have here a simple dictionary of some items so I'm a hammer plier and Nails some prices account an ID and a category now normally of course the this would be a database and then you would probably use something like SQL Alchemy which also integrates nicely with pedantic but for the time being I'm just keeping it simple and I have a fixed dictionary of items here and then actually building out the API is really simple so we have our app variable that I created here what I have here is a simple get request of the root URL the index and that Returns the item in this case a dictionary with a single key items that contains simply the items so how do you run this well that's what you do with uvicorn and in order to run this you write uvicorn and then we say Main and if you pass reload then uvicorn is also going to watch your files and if you change anything in the file it's going to reload the server automatically for you so that's really handy so now you see we started the server and this is the link that the server is running on that our API is available at now I've also got a very simple file here to test this server of ours that we just launched and that use the request package and that just doesn't get request of the index so when I run this you see that we now get as a result back the Json data containing the items and what's interesting is what happens behind the scene here because items is dictionary that contains item objects it's not Json data right it's uh it's a python dictionary containing pedantic objects and what's nice is that fast API handles all the Json serialization for us so even though in Python we're dealing with pedantic objects and we're dealing with dictionaries we get as a result when we do a request Json data and this is really nice this really simplifies things now of course next to using the request package and a test script you can also directly access the API in the browser because it's simply a URL and this is the result of calling that index URL in your browser and this gives of course exactly the same Json data back by the way if you're enjoying this video so far I'd really appreciate you hitting the like button it helps me reach a wider audience on YouTube now next let's add a couple of other endpoints to this API so we have the simple get request here of the index that simply gives us all of the items but let's add one that allows to retrieve an item by ID so then we have ADD app.get and in this case the route is going to be slightly different this is going to be items and we're going to get an item ID like so and what this means is that you can now specify the item id as a part of the URL and let's call this query Item ID and what's nice about fast API is that it's going to automatically transform this query parameter here into an argument of the function so I can have my item id which is an integer and this is going to return an item and then of course first we have to check if the item actually exists so if item id not in items and this would normally be a database query obviously then we're going to erase and http exception which comes from Fast API and an HTTP exception we can give the status code for example 404 which is normally the code you use for item not found and then you can provide detail like item with ID does not exist so then this is what we get so if it's not there we raise an exception and then we're going to Simply return items item ID and again here we don't have to worry about converting to Json because that's what fast API handles for us automatically and now that I've changed the main file you can also see that our server here has actually been restarted so now let's change our script so that we're going to retrieve items zero and then when we run this we get the item with ID 0. and let's also try something else so if I do item 56 which we don't have then this is going to give us an error with the detail that the item with this ID doesn't exist what's also nice is that fast API already validates the parameters for us so here we indicate that item ID is an integer so if for example we try to retrieve an item with an ID that's not an integer then when we run the script you're going to see that fast API handles the validation for us so it gives us some detailed error information that the value we pass is not a valid integer so this happens already before we even run our code so this is a really simple way for us to make sure that the data that we're getting is actually of the right type another thing you can do next to adding these URL rounds is that you can add query parameters and that's normally denoted by adding a question mark with query parameters after the URL and that's often used for example when you have a search interface you want to search for in this case items and you want to provide some query parameters to search for those items so how that works is actually also really simple so let's say we have another endpoint hot dot get and here we're simply going to retrieve the items and then we have a function query item by parameters so we want to have query parameters and now you see we don't provide any parameters here in the URL itself but we can still provide arguments here and those are going to be query parameters so it won't have a name which is string or none so it's an optional query parameter and we can add more like the price for example or the count so then basically this is what we get and then this is going to return a dictionary of our selected items I've created a little helper type here which is a selection which is a dictionary of string two string and Float category or none that's basically the sort of Json data that we can expect as a result so there's a dictionary of string two selection and now we can write the code that actually searches for items that match these things so let's say we have a helper function check item that will allow us to check whether the item is actually should be part of the selection so this is going to return a Boolean and now we can simply check for each of these values whether I actually match with the value in the item here's a nice way to do that in Python all basically checks all the conditions and then returns true if that's true for all of the values so here I'm simply checking that item name is done or the name is the same and same for the price count and the category and then we can do is use a list comprehension to create the selection so that's going to be a item for item in items dot values if check item item like so and then as a result let's return a dictionary containing the original query with the name price count and category and the actual selection there we go here you have an example of a get request for recalling that items endpoint and then passing the name as a query parameter so when we run this then you see we now get the query and the selection which is only a single item namely the nails now you can do more than just gets request obviously you can do Post put patch delete request as well so here I have a slightly more complete example that has also a couple of other endpoints so we have the get request that I added before and then if you look here we also have now a post request to actually add an item and here also we look if the ID is already in the item we erase the HTTP exception then we raise a 400 error and then if it doesn't exist then we simply add it to the items and then we return a dictionary with the new item that we just added and there's a delete that deletes the item so you have all the basic operations that you need in an API let's look a bit closer at how this is implemented so adding an item you see that we do a post request to the root URL and you also see that there is an argument of type item here and this item object is retrieved from the body of the post so you send Json data to this endpoint and again just like when you send Json data back as a result from get request if you have a post request like this then fast API automatically transforms the Json data into pedantic objects for you which is really nice and same thing for updating here you see we are combining these things actually in that update gets a URL parameter which is the item ID that we are going to update and we're also going to get data namely item id name price and the accounts and all of that is again transformed from Json data into these actual argument values and types are all being validated which is really nice and then here we have to delete endpoint that also gets an item id as a URL parameter and that also checks is the item there if not it raised an exception and if it does exist it pops the item from the dictionary and then Returns the deleted item and these endpoints delete and updates they use different HTTP verbs right so add item uses post update uses put sometimes you also use patch and we have delete that use the delete verb so what you can also do instead of having these delete and updates URL structures you can also simply call this items and then the put verb is going to determine what's going to happen with this item ID so in this case for example we have a simple get items Item ID so that's just going to return the item if you call it with put that's going to update the item and if you call it with delete that's going to delete the item so then this is what you get in the end here I have a few test requests so here I'm adding an item so that's a post request then I'm getting the items to see if it's really added then I'm updating an item by calling it put request and then using get to see what's happened and then I'm deleting an item also by using the delete verb when I run this code this is what you get actually you see here there is an error in that apparently I forgot to add the category so let's also add the category here and in this case a screwdriver is of course of the category tools so let's run this one more time and see what happens so now you see the screwdriver was added and it's also in the list of items we see it here at the end we can also update an item so in this case the update changes the count to 9001 of item zero and you can also see that the hammer now has a count of 9001 and same for deleted so we deleted the hammer item so we get the hammer item back as a result from the delete operation and you see it's also no longer in the dictionary of items so here's the first thing that I really like about fast API it's really simple to get started with this and the way that it works together with type hints and using the the app then as a decorator to create the endpoints to me is a really simple way of doing it and because it converts to and from Json whether that's URL parameter first functional arguments results or a request body when you do a post request for example this all happens under the hood and that really simplifies things a lot using The Decorator like this I think works really well fast API is not the only platform that does this flask also has it but I do prefer to have the verbs like get and post as methods of The Decorator I think this is a bit easy to read than having to pass the method as an argument like it's done in flask a second thing that's nice about fast API is that it does validation under the hood using type hints if you provide data that can be interpreted as the type of the objects in Python it's simply going to give you a nice error you can also use that to limit Arguments for example if you want to search for a category which in our case is an enum then fast API is going to check that the value that you pass as a category actually matches one of these you know values and it goes further than these basic data structures so even if you have an item class here because that's a pedantic base model and fast API integrates with that it's also going to do those checks to make sure that the data matches what is expected for the item class so here for example I have a bunch of tests so here we have some get requests that actually work so we have count 20 with an integer category tool so that all works but this request for example fails because there is no ingredients category so this is going to fill with an error so if you run this then you can see that's actually what's happening here so we have here the detail category value is not a valid enumeration member that's permitted and even tells you that you should use tools or consumables here here are some other errors like for example if I do counts with the string which of course doesn't work and you also see that the arrow is here count value is not a valid integer and same thing happens on the object level so if I try to add a screwdriver with count hello which of course is not loud then also you see that we get an error here that value is not a valid integer so that works everywhere through the whole data structure that you define in your python code validation and fast API actually goes further than just via the typings you can also Supply via path and query which you can both import from Fast API that I'm doing here you can also use that to perform to add extra constraints for example here I have the update endpoints well I'm simply indicating here that item id as the path argument the URL path argument should be greater or equal to zero or that the name should have a minimum length of 1 and maximum length of 8 or that price should be greater than zero or counts should be at least zero so these things simply had extra validation flexibility that you can directly Define here in your endpoints which makes it really simple to add those checks here I have a few examples of requests that are going to fail for example if I have account -1 or a negative price or I try to update an item id that's negative or I have a name that's really long longer than eight characters you're going to see that will get all sorts of errors and these errors are generated automatically by fast API which makes it really simple to set up it's just a question have you used Fast API already if so how far have you gone with validating arguments and validating inputs and outputs of your API let me know in the comments and let me know if you have any tips that you want to share on building in validation into your API the final thing that's nice about fast API is that you can automatically generate documentation by simply adding it to your code so here are a few examples so if you create the fast API instance like what I'm doing here you can add metadata like the title and you can add a description you can add a version you can also use doc strings of classes like here I have the category enum you can add a doc string and then this is going to be reflected in the documentation that also works of course for pedantic objects and if you use field to Define fields in your identity class so field is from pedantic then you can also add a description and it's also going to end up in the documentation of your API finally what you can also do is that you can Define using the responses object in your API endpoint what kind of response that should be for each of the status code so if state is called the 400 then this is going to be the description and if it's 404 then it's simply going to State item not found documentation is served by the API itself either using slash docs that's the Swagger UI that's basically what you see here but there's also a redock UI that's served as well that you can see an example of here so I hope this video gave you an idea of how to develop an API using the fast API package and remember it's blazingly fast now there are some people who criticize fast API from not being scalable in fact that's more to do with how python is set up with concurrency and the global interpreter log uvicorn the server that's being used with fast API actually doesn't really take care of concurrency so handling concurrent requests is a bit of a pain but you can use instead of uvicorn G unicorn I'm not sure what's with all the unicorn and UV corns but g-unicorn is an alternative to UV corn that has automatic worker process management and then it scales much better because then you can handle multiple requests more easily another thing you can do up to a certain level is also address this in your Cloud architecture by setting up your load balancer correctly so fast API is pretty good if you want to set up restful API like I've showed you today an alternative to the rest API is graphql which is also really nice if you want to learn more about graphql versus rest and which of these Technologies you should choose for your API watch this video next thanks for watching take care and see you next week
Info
Channel: ArjanCodes
Views: 87,450
Rating: undefined out of 5
Keywords: fastapi python tutorial, fastapi, fastapi tutorial, fastapi python, fastapi 2022, fastapi2023, python tutorial, api python, fastapi authentication, python fast api, api tutorial, fast api, http methods, fast api tutorial, python api, api python requests, api python json, api python project, api python tutorial, api python explained, fastapi tutorial for beginners, fastapi python framework, fastapi python example, fastapi python project, python api integration
Id: SORiTsvnU28
Channel Id: undefined
Length: 20min 38sec (1238 seconds)
Published: Fri Feb 10 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.