Learning FastAPI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello can you guys hear me okay hey muhammad welcome to the stream all right cool i guess you can hear me so for this stream it's pretty straightforward exactly what the title says i'll be learning fast api so um yeah that's all i'll be doing in this video and then you know i can talk to you guys anybody in the chat as well um i've never used fast api before people were telling me last stream to check it out and i've heard of it before but i haven't uh used it so i am willing to learn how it works it's not for flask it has flask like style a flask like style if you go down here you see you have the uh the decorators for the endpoints the the routes that you can create um so it looks like flask but it isn't i'm guessing it's just inspired by flask so um should be pretty easy to pick up since it is similar to flask uh hey cena welcome to the stream all right so let me start up like a a vs code session so uh we'll just call this fast well not fast api but um learn fast api okay yeah it's an independent framework so it's just another uh framework in python for creating web apps specifically apis obviously in the name so um let's see code learn fast api hey ian welcome to the chat welcome to the stream hey uh muhammad welcome so like i said i've never used fast api before i have no idea what it entails i know the syntax or not the syntax but the style is similar to flask but i have no idea how to get it running so i'll just start from the home page of the uh documentation here and then i'll go through maybe the tutorial and uh we'll get something working in the stream uh really what i want to do eventually is i want to create a video as soon as like maybe today or tomorrow to put on my channel it's like an intro to fast api so if anybody is interested in learning the framework i can kind of give them that introduction and then from there they can go and explore more um if they want to learn more about fast api so i have to learn it myself so let's see uh it's a modern fast web framework for building apis with python 3.6 based on standard python type hints okay so um i haven't used type hints at all in python um so that should be new so that's kind of like built into the framework so that's definitely uh different from other web frameworks like flask or django um also it requires python 3.6 so i'm guessing it requires some of the um async functionality that python 3.6 has i've also i haven't done much with that so i guess i'll have to learn that probably um is it better than django i have no idea uh is it like flask uh it has a similar style of flask but just from reading the intro there it's gonna be different from flask as well so uh we'll see uh while you're fast enough you can learn an entire framework in only one day and make a video right after well so there's levels to learning something um really with web development things are pretty similar like you know it's just a different way of doing the same thing so it's not like you're learning something 100 new it's like you're learning just a different style so you can pick it up pretty quickly but i wouldn't say i'll be able to be productive in it after a day but definitely enough to introduce it after a day so there's just different levels to it um you don't see how it's better than flask um we'll we'll see how it compares um shane you have to go to bed um i think this is going to be unlisted so you might not be able to see this but you will see the introduction video when i make it so um yeah check that out so the key features uh fast so very high performance on par with node.js and go um so i'm guessing this is going to be similar to node.js in the sense that um it's an asynchronous framework so if you guys ever used node.js then you know that um it's not like a typical web framework where the code kind of executes line by line like it starts at the top and it goes down to the bottom instead what happens is like different parts in your code can signal the web server to kind of wait for something to happen and the web server can go do something else while it's waiting so in a synchronous server like you go down and you get to a line of code where you have to wait and then you just pause and you don't do anything until something happens and then you continue whereas with the async framework it goes and once it gets to a point where it has to wait it goes to do something else and then it will come back later and then continue so it's almost like it can do more at one time in a sense like technically you can't do multiple things at once with a computer but um practically it feels like it because a lot of times spent a lot of the time and web uh apps it can be spent waiting a bit on what you're doing so instead of just waiting for it to finish you can go do something else uh so let's see um yeah so it's much faster yeah for the the reason um i'm pretty sure everybody's on different time zones uh well ronaldo rolando rolando rolando okay my second monitor is kind of far um yeah it's like uh it's 2 30 p.m here and then yeah it's it's 11 30 there for them uh fast api will replace flask um i think there's room for so many different frameworks and the thing with frameworks that you have to realize is you can always come up with something that's better in a way that's new but really what another thing that goes into any framework or language is kind of like it's community it's history and so on so um you know sometimes it's better to use something that's a little bit older because it's more established and it has a bunch of extensions and people have already solved a bunch of problems that you're going to encounter using it whereas with something new it's like you know everybody has to figure out everything again and that just takes time so um you know old frameworks definitely have an advantage and flask has been out for quite some time uh do some view flash stuff sometime i definitely will i i definitely will i don't know when but i will eventually so let's read the other features as faster code increase the speed to develop features by 200 to 300 that seems a bit of a weird statement i don't know what that means but i guess i will find out when we start writing code like i don't know how you can say well we'll see we'll see i'm pretty sure there's some kind of patterns that they have that reduce the number of lines of code that you have to write for really common things fewer bugs reduce about 40 of human induced errors probably the same thing you just have to write less code so fewer opportunities have an error intuitive great editor support completion everywhere less time debugging easy designed to be easy to use and learn less time reading docs okay short minimize code duplication multiple features uh from each parameter declaration fewer bugs and then um it's robust get production ready code with automatic interactive documentation standards based based on and fully compatible with the open standards for api so it has a lot of um it sounds really good from what their description is of course you know that's not always true in practice but we'll we'll see how it goes um how can we see the direct video later so jonathan i'm going to create a video on fast api like separate from this because you know with the live stream there's a lot of extra stuff that goes on so i'm going to create a streamline video shortly after this stream and you can watch that i don't think you'll be able to see the um the stream but if you really want to see the stream just uh email me um you know anthony prettyprinter.com and i'll give you a link to the stream but it won't be on my channel so um we'll see you remember when flask was first introduced as a joke um i don't really remember back then i don't think i was using python when flask was introduced i don't know it was like um is sql alchemy always your way to go i need to develop connecting to swl server what do you recommend best approach pi odbc would do thanks for all you do uh sql server um yeah i really like sql alchemy um but if you don't want to use uh sql alchemy then basically you'll probably be using some kind of uh direct connection to the database so yeah like um pi odbc which will allow you to connect to the database and then execute queries create cursors and get the the data from the cursor and so on um but i like sql alchemy uh but if you don't like the orm uh then you can just use pi odbc and uh you're welcome jonathan i'm glad i could help you out so let's see uh we have a bunch of opinions here um let's see typer the fast api clies um i don't know what is this typer let's see typer bill great cli is easy to code based on okay i'm not going to use this i guess they just pitched their partner project um so let's go ahead and get started so start up a terminal i'll start up a python virtual environment and then i'll go ahead and install it so you want to call stored procedures already in sql server oh then yeah in that case uh pi odbc will probably be better for you i'm not familiar with any functionality within sql alchemy to call stored procedures but i mean it could be there because sql alchemy is such a huge library and they try to cover different features of um of databases that you may have some kind of uh extension to it or just part of the library itself that allows you to call stored procedures like i know they have things that are specific to postgres i haven't seen anything for stored procedures but they could be there so it could be the same for sql server just check out the documentation um all right so i think it's just fast api right so fast api so pip install fast api pretty simple and then um also for this you need to have a different server so you guys have seen me use flask on this channel in django mostly um both of those have their own built-in development servers and those servers are typical web servers because they use the um there's like a simple web server that comes with python so they're built on top of that um but because fast api is an async framework you can't use the simple python web server so that's why you have to install install a different one so you do the asgi server per for production such as uv corn or hypercorn um so pip install uv corn we'll install that pip install uv corn oh not unicorn uv corn i want to spell unicorn and then uh that's it so we're gonna go through this simple example and i guess i have to learn uh type hints as well and which is good because i haven't really learned it um part of the reason why i'm doing this string is because i've been really slacking on learning new things um you know with the channel like i have a business based around this channel and um it's mostly like flask and django stuff so i found like in the the time that i've been running this business that i haven't really learned anything outside of that um and i feel like i'm regressing as a programmer a bit because i'm kind of limited in what i do so i really need to branch out and do more stuff again so i can grow um yeah let's see so there was an air uh let's see definitely not a small ear um so yeah the wheel always fails for me but uh command um yeah and let me just try sudo i mean pseudo shouldn't matter inside of a a virtual environment but we'll see so a pseudo pip install uv corn and i guess i can't use sudo but let's see um chuck i talked about this last time when it comes to package managers um it's like it's always good you can always find a package manager that works well like at the beginning but like over time as you continue to work on your project like that's when package managers fail and i haven't been willing to deal with another one um because you know i can just deal with pip so i'm sure poetry is great and i should probably learn it but um it's hard for me to know if it's going to last in terms of over the lifetime of a project not so much the library itself uh so let's see the command i don't know let's see i guess we'll we'll see we'll copy this and try to figure out what went wrong just can't let's see i think this is good to copy or let's see can't install uv corn you know what before i do that i'm going to try to install hyper corn because i'm not really concerned with the server that i use so let me try hyper corn before i try to fix uv corn hello marcel welcome to the stream can you please create a comprehensive project course on udemy that shows a scale scalable project structure for a real api in flask um i can consider creating an api course like i created an api course before uh in flask but it's no longer available um but it's still like around uh but i don't it will be on my website if i do create it and it looks like i was able to install hyper corner okay so we're gonna use hyper corn instead of uv corn because i'm not really concerned with the actual server that runs the the app that i'm gonna build i only care about the the framework itself so we'll create a file main.pi and let's go ahead and do this so let me just make this smaller so i can see both the uh the browser and the uh the thing so i used to have this uh window manager on my computer but i bought a new computer and i don't have it anymore so i got to do this manually okay so from typing so typing i'm guessing is from the actual python standard library itself and then fast api is obviously fast api stuff so just like flask you have to instantiate with um the the main class and you have an app object and then from there you can create a decorators not app routes yeah i'm typing flask so one for the index so uh we'll say read root just like they have here and then return hello world so because this is for um apis they can just take a dictionary and convert it to json for you and then app gets we have items and then we have an item id so the item id i'm pretty sure is going to be variable and then we have read item and then this is where the type hints come into play so um it's telling me that you know i need item id in here as a parameter so this is similar to flask but in addition to that i need the type hint and then also there's a queue which is going to be like a generic query i'm guessing and it seems like it's going to be available for every endpoint because i didn't have to mention it anywhere so q which is optional which makes sense that's why i import optional they're expecting a string and it will default to none and then from here it's just like returning the data that is passed in so return the item id and then return q and then that's it right so now we can run the server and let me look up how to run a hyper corn server so um let's see install uv loop i'm going to try hyper corn i'm guessing uv loop is another async web server right or did you mean uv loop to get uv cord to work uh you have two years of hands-on experience with web development should i go for a degree that completely depends on what you are going for because you know some employer in some employers they they um are kind of looking for people with degrees whereas others don't care so much they kind of care more about what your what you've done or um what you can kind of demonstrate that you can do in an interview so um we'll oh uv corn okay okay but yeah yeah so getting a degree just depends on you um one benefit of a degree is that it's going to definitely teach you things that you wouldn't learn on your own uh because you know you just wouldn't come across them um you want to shout out that i made a contribution in courts uh so the court example so yeah i'm gonna cover court so i guess uh when i get to court eventually i'll get to see your example to do so i'll definitely check that out so let me let me try um so pip and saw uv loop uh 0.12 okay i'll try this and i forgot the extra equal sign so i'll try this and um we'll see if i can get uv corn working um fast api better than the flask we'll we'll see um core is made by the same person as hyperkorn okay do i have a degree i don't have a degree in anything programming related my degree is in math uh create a to-do app with auth um we'll see what kind of app i create um it looks like i have errors with this uh and you're welcome thanks for showing up to this stream uh for form validation and rest api what's the best way in flask i find myself restricted sometimes with marshmallow sequel as i end up creating custom schemas for form where fields don't match with my models actually i think that's fine um really you flash uh marshmallow sql alchemy um that's it's just to make it easy for you to uh create schemas based off of simple models but if you have models where um that doesn't work very well then you have to do it yourself there's always going to be code that you write like those libraries are just trying to like save on you writing code that is pretty simple but if you find that you're creating custom schemas then that's completely normal i don't think i don't think there's a such thing as a library that can anticipate everything that you want they can only do the things that are very common so if you have to write custom things then you have to write custom things um so yeah uv loop isn't working either i don't feel like figuring out what's going on so let me just figure out how to start a server with uv loop so or not uv loop hypercoin let me see how to start a server with hypercorn so hypercorn module app so i'm guessing it's going to be like hypercorn and then we have uh main and then app let's see okay so it's running on this and if we go here okay so it's working so we have uh hello world and then if i go to items and pass in an item id like five then we get item id and q is null if i pass in q and just say hello world again we see that q is working as well so let me just see if there's a way to reload the server automatically like there is in uh uv corn yeah so let's do that stop the server and it's slow to stop uh i would use both i would use marshmallow sql alchemy where i can and then i would use marshmallow where i can't uh can you create a docker container development environment and then kubernate and ansible deployment server and testing and product working environment for development production release for sdlc probably not i'm not really into like um like any kind of web op stuff like i don't use docker i just put the code on my server like i i do it pretty simply like i don't find um that to be useful for me um like i understand that it is useful but i just don't think it's useful for me so let me let me try this yeah so reload is working and the server is working okay so i guess we can start the the rest of the tutorial now because i have the endpoints working and it should be async so let's go back to the documentation check it uh we'll see that as the response so you already create an api that receives http requests and the path slash and slash items item id both paths take get operations the path um items item id has a path parameter and it should be an integer and then the uh other one has an optional stir parameter for a keyword for the queue query okay so if i do items and then put in a string i'm i'm expecting this to fail somehow so it's expecting a number so five an integer so if i do something like five like this i write it out i get this error right away it says um you know item id value is not a valid integer type error dot integer so i can see like an advantage already over other um frameworks when it comes to an api because this one you don't have to um put any error checking for a case like that like it doesn't crash your app um it gives a useful error message um so that's that's nice to see so let's go back and we also have interactive documentation so if i go to docs swagger works and then i can use this and then try it out execute um we get the response hello world and then for items i can pass in an item id i'll pass on a six execute and i get the response so this is nice it makes it uh easy to test the api's in the building and i can see the results here i can see um all the all the header information as well so that's good so alternative uh api docs so redoc so redoc and they have another one so you can get this uh how do you get it like how do you like is this like swagger where you can actually run it or does this just show you um okay so uh am i using python 2 because using pip instead of pip3 no i'm using python 3. i have an alias for python 3.8 to just the word python and then for pip i never use pip outside of a virtual environment so when you create a virtual environment with python like three whatever whatever version number you create um the virtual environment in then the pip will be for that major version so if i'm using python 3 to create a virtual environment then it's going to use pip3 automatically all right so we're going to modify this to get a put request so pedantic i've never used pydanic before but i think it is some kind of schema tool kind of similar to marshmallow so we're going to create a class called item and it's going to take in the base model from pedantic and then similar to the um the functions we're using type hints here so name is going to be a stir price is going to be a floats and is offer is going to be optional and then bool and it's going to be default none and i'm actually not familiar with this syntax so i see i have a class here and i guess i can just declare attributes with no um values so for instance i'm kind of used to this so i can create a class like this and if i have a name i can say name equals you know whatever and then i can have a price you know one two three um and is offer which i spell it wrong um but with this you don't have to assign anything so you know i'm guessing that's just a common feature of the type hinting and that's just something that i'll learn over time okay so let's create the new endpoint is fast api better than django rest i have no idea like this is my first time using fast api and i'm pretty sure both have their advantages even though i haven't completed uh working with fast api i'm pretty sure there are things that uh the django rest framework will do better like i was saying earlier like um in addition to the framework itself like a lot of what goes into a framework or a language is the community and the history behind it so the rest framework has been around for a while there's a lot of documentation there's there are a lot of um you know questions on stack overflow there are extensions so um you have to take that into account when you want to use something you don't want to always use the newest thing because you know when you get stuck you may not have help to get you unstuck right you don't want to ideally when you're writing code you don't want to like fix errors in the framework itself or limitations in the framework itself like you're just gonna write code and get whatever you're trying to accomplish done so this one has a type hint for uh item id and then we're gonna say that the item is going to be the type of item which is this class so um this should be a colon here and then um we're going to return the item name and that's going to be item dot name and then we're going to return the item id right so item id right so where does this name come from let's see so we're putting oh so it expects the item and then the name comes from here so i need to pass in at least a name and a price so let's take a look at this if i go to swagger so doc or docs right and then i go to items so yeah this makes sense so we have to pass in an item id in the url because it's here so let's say five but in addition to that we have to pass adjacent object in the body which has to have the same form as this so at a minimum it has to have the name and the price and then we can have is offer uh to be there if we want so the name will be anthony's item and the price will be 200 and we'll say is offer false so we'll execute this and it returns the item name so anthony's item and the item id5 so that's pretty easy to do um and i see i definitely like the uh the style of this so uh one of the things that you do a lot when you're creating api is you have to kind of create the connection between the data that the user is passing in with uh you know things in your code so normally you can use something like marshmallow for that so you create like a marshmallow schema and you bring in the data and you you you take the data so let me let me just show you marshmallow really quick you don't necessarily have to use marshmallow but you can use that for um in python so let's see an example here would be not this one uh serializing no deserializing okay so for example like you have some kind of api endpoint and it takes in the user data right so in this case this would be similar to the item that i created and you have to have a schema which is you know the same in this in both cases but you have to load the data directly so you call schema.load on the data that was passed in and then it handles it for you from there and it can do validation at this point as well when you load it but um with fast api like they take advantage of the type hinting where um you can just say that an item the the data that the user is passing in is associated with the schema so you don't have to do it yourself i'm kind of curious how they do this in the code like how how they do because if i recall correctly like the type hints in python don't actually do anything so i guess it's kind of cool that you as a programmer can kind of take advantage of those type hints and modify your code in different ways um when you get flask freelance work do you ever feel like you couldn't do this uh couldn't do what um you love fast api thanks pretty printed your vids have helped me so much i'm glad i i'm glad i could help you um so let's see so that makes sense with the put requests and associating the the data with the schema that i created and it reloads automatically uh it does that i already did that let's see oh these are very uh thorough docs you know they're telling you to press the button i don't really care about the alternative documentation so in summary you declare once the type of parameters body et cetera is function parameters you do that with the standard modern python types you don't have to learn a new syntax the methods or classes of a specific specific library etc just standard python 3.6 for example for an ins item id int or for a more complic or complex item model item item and with that single declaration you get editor support including completion type checks which you know i don't have enabled on my editor a validation of data so automatic and clear errors where the data is invalid validation even for deeply nested json objects so that part is pretty nice a conversion of input data coming from the network to python data types reading from json path parameters query parameters cookies headers forms and files okay that's also pretty good conversion of output data converting from python data and types to network data as json so convert python types stir in float bool list etc date daytime objects you would objects database models and many more okay so all this is really good because uh you don't have to convert it yourself so as an example i know in flask so here's what i'll do i'll create like a second project in flask and we'll kind of compare uh what needs to be done in flask with um a fast api so make directory flask api example and i'll open that up so let's see um couldn't do that freelance job um i've never had a case where like i felt like i couldn't do something like i know there are things that i can't do or at least i can't do within like a reasonable amount of time but for all the jobs that i've done it's always been pretty simple like it's pretty easy to imagine something that would be too difficult but in practice like you're not gonna come across that at least in my experience especially for like a freelance job like anything that's going to be super complicated it'd be odd for them looking for a freelancer to do it typically freelancers are going to do things that are fairly well defined and if you have experience you should be able to handle them given enough time have you worked with the full stack postgres fast api repo it's really good but also complicated if you're not familiar with every aspect of it tutorial can make for a good video series so adam this is my first experience with fast api um so i haven't even heard of that but i'm sure i'll get to it eventually i learned about almost everything about python from your channel brother thank you so much you're welcome i'm glad i can help you out with that um so what i'm going to do is i'm going to demonstrate like an example with a flask compared to fast api just to show you like the the code difference and just to help myself understand the difference as well so we'll install that okay so from flask import flask and then app okay so the thing that i want to focus on was uh returning like a daytime object right so app routes get time and i'll just show you what needs to be done so get time so i want to return like a a response like this so return just time and i want to get the current time so i can import date time so from day time import date time and then i can do a date time dot now right and if i try to run this we'll see there's going to be an issue with this so get time actually no there is no issue with that so i guess that's nice it's it's converting it to a string automatically so this is a daytime object but um something here is converting it to a string um so i don't know what that is in flask but i guess that's that's pretty nice so let's look for a different one that wouldn't get converted automatically okay so database models so that's a good one but i don't have any database models yet so when i get to that i guess i can demo that but um daytime objects automatically get converted in flask and obviously in fast api because that's what it says here then automatic interactive api documentation including two alternative user interfaces uh swagger and redoc okay so um that's pretty nice um that shoe i'm what i am now in flask is from your videos so thanks for making such valuable content i'm glad i can help with that and hopefully if you do you have a freelance job and you get stuck on something hopefully i have a video somewhere that can help you out with that okay so coming back to the previous code example fast api will validate that there is an item id in the path uh validate that it has the right type check for an optional query parameter for put requests read the body as json okay convert from into json automatically document everything with open api that can be used by interactive documentation systems automatic automatic client code generation systems for many languages and provide two interactive documentation web interfaces directly so that's um that's really good like i i actually like this so far it's pretty cool i can see how people would prefer this over something like flask uh hey cenon uh nice to watch my video live well it's good having you here um i like editing code and vim in full screen console mode um i like vim2 i just don't use it that much anymore like i really like vs code um but yeah i i had my start with vim when i started programming seriously so it has a special place in my heart even though i don't use it as much anymore um we just scratched the surface but you already get the idea of how it all works try changing a line with that from and then see how your editor will auto complete so let's see oh yeah it does so that's nice i didn't even realize that i didn't think it was enabled by default but yeah item.price so yeah that makes it a lot easier when you're writing the code it will um it'll fill it in for you so many times like i forget the name of my own attributes and um i have to like go back in the code to see like what i called it so that's pretty nice so uh for a more complete example including more features see the tutorial user guide spoiler spoiler alert that tutorial user guide includes a declaration of parameters from other places such as headers cookies form fields and files how to set validation constraints as maximum length or regex a very powerful easy to use dependency injection system security and authentication including support for oauth 2 and json web tokens and basic auth more advanced techniques for declaring deeply nested json models and many extra features thanks to starlet as websockets graphql um tests based on requests and pi tests cores cookie sessions and more uh performance independent tech empower benchmark show fast api applications running under uv core as one of the fastest python frameworks available only below starlet and uv core themselves used internally by fast api to understand more about it see the section benchmarks so some optional dependencies and then license okay so cool so we made it past the first page so so far my first impressions are i really like this um it's definitely an interesting way of working with this so kind of like flask was one of the first libraries to take advantage of decorators in python to kind of make it easier for you to do things in a web framework because with django if you're familiar with django like you have to associate functions with urls kind of separately whereas in flask you combine them into one thing by using decorators and of course you can um associate them separately like you can create standalone functions and you can have like a add url rule if i recall correctly on the app object and associated with it but using decorators just makes it so much more simple especially if your view code is pretty small so fast api does that but it goes even further by then taking advantage of another feature of python type hinting to allow you to do things um without having to write a bunch of codes so i i like it so far so your channel is possibly the best channel for django and flash content i guess it would become the place for fast api to now um we'll see we'll see are there any other channels covering fast api does anybody talk about that um like i try to keep up with what other channels are doing but you know it can be difficult like i have like 200 channels in my subscription that are programming related and you know it's hard to know but it would be nice if i can become the channel for fast api potentially that would be nice um all right so we're going to go through this uh tutorial now so i did the the quick start tutorial and i got to see a lot of the features of fast api right away so we're going to go with the the regular tutorial so does anybody here like uh develop apis for anything what do you guys use apis for because i know like for me the the common use case for apis in my case is um a web hooks like i have uh some web hooks running and that's basically an api and i wrote it in flask um so that's the thing that i have running and then you know i i create random apis for other stuff but the thing that i have running have had running for the past couple of years is uh a web hook so not many i can find in april oh so we'll see um the more channels are popping up uh plane needs to use api for e-commerce flask cap so uh how like what part of the app is going to require an api for the e-commerce app i use apis for communicating two independent codes um yeah like if you have uh things that need to talk to each other then apis work well yeah twilio is a good example of using uh apis for stuff model deployments i use api for front-end frameworks like react okay yeah that's um that's a really really big one yeah so that's something that i completely overlooked because like i don't do anything with um front-end javascript frameworks but i should uh but like my problem with front-end frameworks is like there's really nothing wrong with them um by themselves i just feel like a lot of people use them without needing them like i think the reason why you would want to use a front-end javascript framework is mostly for user experience but if you don't need user experience then you may not want to use a front-end javascript framework but that's just how i look at it but i do understand that user experience can be pretty important so it just depends on what you're building and who you're building it for and as i cover more stuff with like javascript on this channel when i get back to it then i'll definitely create apis to be consumed by javascript apps and um who knows maybe what i'll do is i'll also learn something like view more completely and i'll create an example app using like fast api in view and i can show you how to combine them and uh get them working well together so we'll see um so let's get started on this uh user guide intro so this tutorial shows you fast api with most of its features step by step each section gradually builds on the previous ones but it's structured to separate top rigs uh structure two separate topics so that you can go directly to any specific one to solve your specific api needs it's also built to work as a future reference so you can come back and see exactly what you need so run the code all the code blocks can be copied and used directly they're actually tested python files uh to run the examples copy the code from main.pi okay um yeah using the editor i've installed it already um okay so this is kind of like a rehash of what i did so this part i've done and the difference between uh my code and this one is that it has the async on it so i'm guessing that's not going to change anything about how it runs um i guess later i can look into what the differences so let's see so read roots try it out execute yeah it still works the same uh i'm making a fast api tutorial but it will be in my native polish language okay so we don't have to compete with each other then so i'm sure that would be good video though um is there a lot of content out there for programming in polish like if i only speak english so i only know about the english youtube um api with ujs okay i'm working on a project now with fast api support a discord bot okay that sounds interesting um what made you choose python based frameworks over node.js while node was more popular always um i learned python well no actually i learned javascript first um like i don't know i don't know why i chose python based web development over javascript like i've done a little bit of stuff in node but i don't know i guess i like python more maybe like uh as a language i definitely like python more than javascript but as a framework uh node versus like flask really i don't have any uh preference for either one more than the other i can't thank you enough pretty printer i asked this yesterday and you responded thank you so much well you're welcome um does that async method run without event loop i have no idea i have to look more into fast api to see how it works i guess later i can kind of test things to see what the difference is between adding the async and not having async not too much with good content and i want to change it well if you can change it then everybody will come to you to learn programming so that would be nice you'll get all the viewers in the language like there actually is one other language that i know like i i know a little bit of thai and like looking at thai youtube is like you know there are fewer like creators there so like they get more views because like there's just less competition so the people who take the time to actually build channels in like that language they can get more results because like the demand is still there people still want to learn programming it's just like you know there's not um there's not content in the language so anyone who does create it like they'll have an easier time whereas like in english like you know there are so many different channels so uh everyone's views are kind of split among the the audience okay so i have the server running already this is kind of like a repeat of what i did so i'm just skipping over the part that i did um so this is i've already done all this and i guess this is a little more specific so let me just read so create the fast api instance create a path operation and then it has one of the methods post git put delete yeah that makes sense and then um define the path operation function so it goes directly beneath and you can use a normal function so let's see async in a hurry if you are using third party libraries that tell you to call them with the weight like that then declare your path operation functions with async def like this if you're using third third-party library that communicates with something in a database and api the file system and it doesn't have support using a weight um then the clear path operations normally okay that makes sense yeah so um at the moment i won't be using anything that uses a weight so i guess it doesn't matter if i use async or no async but as soon as i need something that's asynchronous inside of the function then i'll have to make it an asynchronous function okay so that that makes sense all right so i'll just leave off the async for now and then when i get to asynchronous things that's when i'll um add it back so return the contents uh message hello world you can return a dick list singular values stir int you can return pedantic models and there are many okay yeah yeah so everything here is what i've already done on the first page uh quick plug the pretty printed jingle course is great uh yeah i i do have courses like a lot of people don't know this and i need to like kind of advertise it more but if you go to courses.prettyprinter.com or justprettyprinter.com you'll see them on the home page as well like i have courses available both uh paid courses and free courses so if you want to check those out if you haven't already uh just go to my website prettyprinter.com and you'll be able to see all of them and see what videos and topics that i cover in them um the goal is to create an internet of things project that writes to fast api and have ujs frontend all dockerized and um continuous integration deployment that that sounds um that sounds like a lot so that sounds like it'd be a really good tutorial so uh let me know about it when you complete it like just send me an email uh anthony prettyprinter.com and i'll take a look at if it has the english subtitles um okay got it when you have asynchronous library they see use async yeah so i haven't used any asynchronous libraries in python at all so that's all new to me so eventually i'll get to it and um i'll test it out is fast api anything like twisted if so please warn me um twisted is um uh kind of similar to fast api in the sense that it's uh async framework right so please warn you um what problems have you had with twisted because i've never tried it before yeah event driven networking engine yeah it's it sounds like it's similar to um node in the sense but just looking at the code example here um it doesn't look user friendly in the same way that um that fast api does like one things i notice is like even for me like reading this here i can completely understand everything that's going on but it still like feels more intimidating than this like uh the fast api stuff is easier to understand at a glance than this even though this is still pretty simple so when i look at the two examples it's like oh i don't want to use twisted because um you know it's it's more effort to do something um but i'm willing to use fast api because just looking at it it looks good i think that's one of the reasons why python is so popular because um you know when you look at python code like it looks like it looks approachable um whereas uh when you look at something like c like it just looks like so cryptic so someone is more likely to gravitate towards python because they feel like it's more approachable uh okay i'll notify you but fast api core code base must stabilize i started six months ago and all the first lessons must be rewritten yeah see that's the problem with these new frameworks is um you know they they have to change things because they figure out the limitations and it causes everyone to have to change the code so that's why it's better than uh that's why sometimes it's better to use something that's old because you know it's not going to change on you um python is like a computer talking to you in your language yeah like it's it's pretty easy to read um so i'm pretty sure that's why like they like teaching beginners with python because it reads like a natural language so back to the tutorial path parameters um i've covered the path parameters already in the first tutorial and then you can add a type to the um the function and you don't necessarily need to have a type so like if i take away the ant here let's try this so i will go back and refresh and then get this and you know before like if i typed in a string it will fail but now because uh i took away the integer type hint i it works so like if i do this again if i run it and then i just type in some random string and execute um it actually just gives me an error in swagger itself saying that this must be an integer but if i try to do it directly like like this we have items and then just some random text then we get this error that is not a valid integer if i take away this type hint and refresh then it works again so uh that's pretty convenient uh data conversion if you run this example and open your browser you will see a response of three so yeah it returns the the number itself as an integer instead of a string so instead of having six in quotation marks it's just six and data validation that's what i just saw the documentation gets generated automatically uh pydank so all the data validation is performed under the hood by pydank so you get all the benefits from it and you know you are in good hands you can use the same type declarations with stir float bull and many other complex data types several of these are explored in the next chapters of the tutorial all right the order matters when creating path operations you can find situations where you have a fixed path like user slash me um yeah so because they're evaluating where do you need to make sure that the path user slash me is declared before the one for users slash user id so that's a little well actually that makes sense so um like i know in flask you could like just stack these decorators on top of each other to call the same function but in this case like you want these to behave in completely different ways so for me there is no actual user id so you don't want to have a user id parameter whereas for the other ones you have the user id so let's go ahead and add that so we have app git and then user slash me and then we'll have the function user read me and then return user id is going to be the current user and then we'll create a second one so users and this one has a user id associated with it so let me add this here if i can type it so user id and then read user user id and this is a stir and then return the actual user id okay so let's go ahead and run this code i'll just go directly to it instead of using swagger okay so user slash me i get the current user and then if i do like five i get user id five if i do anthony i get user id anthony but if i do it in reverse so if i put the one with the variable value in it first it will still give me anthony for the first one but if i try to have me then it gives me my username as me because it completely skips over this so it just executes from top to bottom in terms of um figuring out what a path is associated with with function so that makes sense there's something to keep in mind so i'll move that down so let's see um ui fast api docs is much better than the other ones you just opened uh yeah it definitely is so uh you never use it but encode slash databases on github looks very nice for async i have to check that out eventually do you think django is still worth it for web development noobs yes it's definitely worth it um it depends on what you're building but it's definitely useful uh do flash django still relevant but flask is easier and more lightweight yeah flats is gonna be easier to learn um but django is still good um just wanna know if this video will be uploaded to the channel or playing to delete it it won't be deleted but it's not going to be like uh you won't be able to see it on the the uh the video page so if you want to see it just let me know um and i can send you a link uh just a tip guys there is a database rm focus on work with async frameworks called tortoise rm i believe it was designed to work with fast api so yeah um i guess i'll have to use tortoise eventually uh when i get to the model stuff um with the asynchronous part really a big deal what is the use case for this feature so um the use case for the future is uh in web frameworks like there's a lot of waiting for stuff to happen uh so for example like if you're writing data to the database um you know the writing the data isn't really performed by the web framework itself it's basically like your web framework tells the database that some data needs to be written and that data will take some time to be written and in a regular web framework like flask or django your uh app is gonna sit there and wait for the process to finish so if it takes like two seconds to write the data it's gonna wait for two seconds to write it that means like there's gonna be a thread on your server that's waiting for something to happen which is one less thread available for other people to use if they're trying to access your app um whereas with the async one it's not gonna wait for it to finish instead it's gonna do something else so it can fulfill another request and then it will just come back later and um you know return the result once it's done so it gives a perception that things are faster because they can do more things at once um it's 4am on my side and i think i should really sleep now um yeah just just let me know if you want to see it it won't be deleted but it won't be public uh fast api versus django rest framework um i guess i can cover that as i learn more about it um did i attend the flaskcon no i did not i completely forgot about it like i knew about it going ahead of time and i just forgot about it on the day that it happened or the weekend that it happened so i wasn't there um asynchronous is like threading but an interleaving way threads are painting the ass in terms of threat safety yeah so um yeah it's like it's not so much that it's faster in the sense that things are happening faster it's just like it's not waiting so it's kind of like a perception that it's faster and practically it's faster um i'm guess you're asking about the the flask on yeah you can go on youtube and see the flask on stuff now all right so let's go back to the path parameter stuff and we just did order matters and then predefined values so if you have a path operation that receives a path parameter but you want the possible valid path parameter values to be predetermined you can use a standard python enum so i've actually never used enum before in python so import enum and create a subclass that inherits from stur and from enum uh by inheriting from stir the api dex will show we'll be able to know that the values must be of type string and will be able to render correctly then you create a class attribute with fixed attributes what am i reading then create class attributes with fixed values which will be available for valid values okay so let's try this out so from enum imports enum and then i'll create this class so model name and let's see so model name and then stir and enum okay so alexnet alexnet um resnet in linux and then we have this get model function down here so app gets and then model model name i get model so the model name is going to be that enum that i just created so if model name is equal to modelname.alexdent okay so this makes sense model name and then the message will be deep learning for the win if model dots oh this should be wait a minute model name dot value okay okay i see so model name.value is return model name and then message lcnn all the images and then if it's something else we're going to have model name again along with the message and then have some residuals okay so let's try this one out so we're going to try uh model and then let's see alexnet so we have alexnet there as one of the values in the enum and we can also have resnet and then have some residuals and then lynette or pretty much anything else uh well actually now it has to be one of the values of the enumeration so uh lenet and it returns that and in this case it returns an error because it's not one of the values so that's pretty nice if you have a model where you only have a certain number of things that you can take in um let's see you guys talking about async still uh salary is good for async stuff a good way to understand async is to read something about the event loop and node.js yeah user gets quick response data are handled on server and background available when they are processed in async you don't have to worry about thread safety because only one part runs at a time unlike threading you're awesome just wanted to say that before signing out really awesome uh thanks thanks for showing up to the stream like each one of you is it's awesome to have you here it's it's nice to have people who take time out of the day just to watch me learn fast api so thanks for showing up okay so we covered that part with the predefined values so that's nice and now they're just kind of explaining how it works and then returning them okay so path parameters containing paths let's say you have a path operation with the paths files slash file path but you need file path itself to contain a path like home uh john doe my file dot text so the url for that file would be something like files homes john doe myfile.txt open api doesn't support a way to declare a path parameter to contain a path inside as that can lead to scenarios that are difficult to test and define nevertheless you can still do it in fast api using one of the internal tools from starlit uh and the docs will still work although not adding any documentation telling that the parameters should contain a path so path converter using an option directly directly from starlight you can declare a path parameter containing a path using a url like that in the case the name of the parameter is file path and the last part path tells it that the parameter should match any path so you can use it with that okay so we'll try this so app gets files file path and path and then read file file path is stir so we see the difference there then return file path file path okay so let's try this so files anthony desktop file and we see not found so did i save this let's see let's try that again so i don't know why that's not working so you need the parameter to contain slash oh i need two slashes so slash slash nope that doesn't work either you need you could need the parameter to contain slash with the leading slash in that case the url would be slash files slash home yeah that's not working for me so dude.text yeah i'm not sure about that one it it's making it seem like it just can't find the files so let me try that again so we have files here and it says not found so if i have like files two it's not found so it's almost like this isn't defined so um file.txt that's weird closing bracket oh okay that makes sense okay there we go yeah so that bracket was important so anthony desktop and then file.txt okay yeah so thanks for telling me that um let's see uh when using asyncio is there any need of running multi-threaded anymore i'm not sure about that one um how does an api interact with active directory group memberships i'm not really familiar with active directory threat safety can cause big problems if you are not careful for instance gui loops must run on main thread but your worker threats sometimes communicate the gui part like message boxes progress bars like can they be used at the same time yeah like i'm not familiar with async yo so um i don't know the answer to that question and yeah you guys told me about the typo okay so yeah that makes sense now so recap we have the editor support we have the data parsing validation annotation and documentation and you only have to declare that once so it's it's really nice so far i'm really liking this framework so far um i can definitely see the advantages of using it over something like flask to build an api so i like it we declare other function parameters that are not part of path parameters they are automatically interpreted as query parameters um so let's see we have these fake items in a database uh and then you're reading items that has a skip and a limit and then you're returning something okay yeah so if they're not defined directly in the um in the path then you have to put them as arguments and they get interpreted as the values in the query string so for the one with q i added q in the parameters here which was optional so that's why it works so i guess i'm doing something similar here so i'll create this fake database so fake db and then we'll have um item name foo item name uh bar and then item name baz and then we'll create the path so items and then read item skip it's going to be 0 by default limit is going to be 10 by default and then return fake db and then we want to skip and skip plus limits okay so if i go to items i don't know why this one has australian slash i don't like how that one has a trailing slash but the other ones don't so we have uh items and then if i want to skip the first one then i can i get just bar and bass if i want to limit it to just one so limit equals one i can do that if i make the skip zero limits of one i get foo if i limit it to two i get foo and bar okay so that makes sense it's pretty easy to deal with so all the same process that applies to path parameters also applies for query parameters editor support data parsing data validation and automatic documentation and then we have the defaults um yeah so this is really really nice and then uh it can be optional as well it can be none fast api is smart enough to notice that the path parameter item id is a path parameter and q is not it's a query parameter yep yep okay so one thing i like about this so far is the documentation is really good like that's one of the problems with um a lot of things that get created like the documentation is just not very good so when people go to learn it like it's just really difficult because they have to figure out a bunch of things on their own but it looks like fast api they're really helping you understand everything understand everything to learn how it works okay so um query parameter type conversion so you can declare bool types and they will be converted um let's see so we're just adding on to this so what i'll do well oh no this is for like an item id so we'll create this so app gets and then items an item id and then read item item id stir q which is an optional string and it defaults to none we'll have a short and it's going to be a boolean and false okay so item is going to be item all right let's see item id then if q and then item dot updates uh we'll put q inside of the item and then if not short item dot update and then description so description this is an amazing item that has a long description okay and then we return the item all right so there are so many different things that can be done for this so for items we'll do an id so we'll just say anthony and what did i mess up here so item id is a stir and then we have optional and then we have bool is false so somewhere i messed this up so item slash anthony let's see item id oh read the name of the function is the same uh let's call read items well that's not the error so uh if i go to items like that it still works but if i go to item id it doesn't work slash test let me go to the doc let's see what the doc says so we have oh i already have that well no i don't have it already so read items try it out item id anthony execute not a valid integer what did i put as an integer like path item id it's like i feel like i'm missing something really obvious here yeah this one works when i put an integer but like i have this declared as a stir here so it's like it's something interfering we have items oh okay yeah i have another one called items up there okay that's we'll call this um uh get items okay yeah all right so uh get items and then anthony okay yeah so this is amazing long description and then we can have the q in there so q equals q equals tests we see that and then if i add the short short equals false um it's false by default so sure equals true and then it works okay so yeah it was the same route um let's see multiple path and query parameters you can declare multiple path parameters and query parameters at the same time fast api knows which is which and you don't have to declare them in any specific order so they will be detected by name so um let's see yeah you can declare the user id first the item id the queue and the short so let's create this one so app get users user id and then items slash item id and then read user item this is going to have a user id which is an integer an item id that's a stir cue that's optional but it's also a stir and then a short that is boolean that defaults uh false and then um we'll create the item that needs to be returned so item id and then item underscore id owner id is going to be the user id and then if q we're going to update this item with the um with the new one with a new value queue if it's there and if not short item dot update this is pretty much the same thing as before we're going to update the item with the description this is an amazing item that has a long description okay and then return item okay so let's try this so this is going to be users and then user id will be um an int so user id 5 and then the well shouldn't the user id be a string no item id is gonna be a string so um items and then um you know let's say python so the item id is python the owner id is five yeah so that works pretty well okay so let's go down to um require query parameters when you declare a default value for non-path parameters for now we have only seen query parameters then it is not required if you don't want to add specific a specific value but just make it optional then set the default as none but when you want to make a query parameter required you can just not declare any default value right so the item id is a stir and then needy is a stir so we'll have to pass needy in the query string so let's go ahead and create that one app get an items item id read user item two i'll call this item id stir and then needy stir and item equals item item id needy needy return item all right and then i can go to items and once again it's the same like i don't know why they keep reusing the same routes um we'll call this um items with two s's how about that so items with two s's and item id five and it gives me an error saying that um i need the parameter needy so i'll have the query string needy equals true and then we see it there so as long as you don't pass in uh none here then it's going to be required by default so that's nice uh can values be typed with names like in a parameterized url um well do you mean what we're doing right now so like needy will be a parameter in the url and it's required could you hide explorer so we can see a little bit more code yeah sure that's that's a good idea um like there we go okay yeah um change the url yeah yo yo so they keep reusing the same url so i have to keep that in mind all right so i just did that and we get the error like i just saw and yep yep so and of course you can define some parameters as required such as having a default value and some entirely optional yeah so that's kind of a natural extension of that so i'll just um add it so skip zero uh limit optional int none and then um we can just pass those in here so skip is going to be skip and limit will be limit all right so if i run this again it shows me zero for skip and null for limit and i can just add those if i want to so limit 10 yeah so this is all really nice so far so i really like how it takes advantage of just python features to get this to work instead of um you having to declare everything yourself like declare that certain things are optional or not so like uh when you're using something like marshmallow you would have to create like an entire schema that represents all the things that you can have as parameters to your endpoint but with this you don't have to create a schema you just create these type hints and then fast api will do everything for you so that's really really nice so request body okay so this should be getting into um dealing with things like cookies and headers i'm guessing pydanic is awesome yeah it's it's looking really nice okay so um request body when you need to send data from a client let's say a browser to your api you send it as a request body oh okay so this is not what i'm talking about yet this is just like json data that i covered in the first one but we'll see it again here so request body is data sent by the client to your api a response body is the data is the data your api sends to the client your api almost always has to send a response body but clients don't necessarily need to send a request body to declare a request body use pedentic models with all their power and benefits okay so i've already did the base model so i'll just expand it so i have this item up here and we have a description that we're going to add to it just optional stir none and then we have a tax so that's optional to float and it's going to be none and then we can simply make a route where we can create one so we'll create a post request and this is really nice because it looks like you don't have to do anything at all to make this work so create item and then item is going to be that item model that we just created and it just simply returns the item that we create so it just gets uh mirrored back so if i go over to um well let's see is there anything more no yeah so if i go over to uh swagger and then i go to create or is it create item so post requests on items then it tells me what the example is and i can try it myself and it gives me placeholders so the name of the item will be anthony's item it's going to be 100 is offer false and then the description will be uh this is the new item that i'm adding and then the tax will be 20. if i execute that i should get the same finger response so um yeah this is really nice so really in three lines of code i'm able to create an end point to create a new item so this handles the uh the create part of crud and three lines of code of course you need the schema but you know that would be defined anyway so uh line 87 has items yeah i did that intentionally because uh in the examples like they keep reusing like items over and over again and i got like a name collision and i had an error so i just created like a second one to cover this example because i i did the first tutorial on the first uh page and it had me create like items and then like now i'm going through like the longer tutorial and it's still having me create items i guess they really like items so um i had a name collision that's why i added the xs um so yeah everything that i just talked about i did here and then um let's see declare as a parameter yeah so with just that python type declaration fast api will read the body of the request as json convert the corresponding types if needed validate the data and it will return a message if it's uh invalid i give you the received data in the parameter item and then create a json schema for the model and then they'll be part of the documentation which we saw we see the automatic docs here we have the editor support again um and then this is about this is not by chance the whole framework was built around that design and it was thoroughly tested at the design phase before any implementation to ensure that it will work with all the editors there were even some changes to pydank itself to support this the previous screenshots were taken with vs code but you would get the same editor support with pycharm and most other python editors so yeah like if i do like item dot tax it's there if i do item dot description it's there if i do item dot um price it's there so that's that's really nice it's it's something i've never really thought about like i never really thought about a framework making it easier to write code in the editor but that's really nice i've never seen that before i love the pythonic path because it focuses on the simplicity of learning and using the language it calls out unnecessary things like brackets and force enforces a specific coding style to make code readable and accessible and uses many language features to automate and simplify work pydenic is a great example of this um cool feature of python if your code looks ugly you're it's probably wrong yeah so python is really great about that just um just how it looks is really approachable and yeah if your code looks bad then that is a good thing because you can write some ugly looking code in other languages um so we have the the editor support so now let's go back down here and let's see so we converted to a dictionary and then we're gonna update the dictionary okay um okay yeah that confused me for a second so this item is not a dictionary it's it's something that can be converted to a dictionary but it isn't a dictionary so we can't simply just update it directly so we have to convert it to a dictionary first then update it and then we can return it and then uh fast api will convert it back to the item and then of course convert it to json data so the user can see it so we'll have item dictionary equals item and convert it to a dictionary if item.tax will have price with tax is equal to item.price plus item.tax and then we'll update the dictionary uh with a price with tax and then return that dictionary so let's try this one out so let's go back here so we have the price is 100 and the tax is 20. so when i run this the price with the tax should be 120. so let's execute this and we see that here price with tax is 120 so that's that's really nice um so request body plus path parameters you can declare path parameters and body requests at the same time uh fast api will recognize that the function parameters that match path parameters should be taken from the path and that function parameters that are declared to be pedantic models should be taken from the request body uh so yeah i kind of covered that before but you know that makes sense well actually you know what part so the request body so before like the item here um you know if it was analogous to this one you know the needy has to be a part of the query string whereas with this one this is part of the request body so i'm just guessing it's um it's based off the the method oh okay well it's going to answer my question down here so you can also declare body path and query parameters all at the same time fast api will recognize each of them and take the data from the correct place so here we have item id is an integer which is from the path uh we have item which is an item that should be from the request body and then we have hue which should be optional from the request string um so you know let's let's try that one out let's see what happens when i do this i have a test for this so um we'll create the put method so app now put we have items and then item id and then create new item and then this is going to be integer item is going to be an item and then q is going to be optional stir goes none and then results will have item id item id and item dictionary there we're just going to add them in there and then if q results dot update q as q and then return the result okay so let's see what this looks like in swagger so refresh this invalid syntax uh that's not returned that should be results and i need to restart the server okay so i'm looking for a put and once again well i don't think i had any other put requests so um try it out okay so i'm thinking by default like the body should be the pidanic model whereas anything in the query string um will be different so what i was gonna try was this so i was going to put q down here to see if it works and i can't like tab inside of this so q equals uh this is the query string so let's see if this works so item five execute this and then i get an error because um this isn't valid so what's missing expecting property name enclosed in double quotes for body like well let me take this out first and try it oh it's not javascript it's json i can't have this trailing comma all right so it's it returns like it's ignoring the query parameter so if i add you know new query parameter here no okay so let's see first do i have any other put requests for this just to make sure it's not interfering yeah it yeah it does okay so let me remove this before i go any further and then refresh the page okay so create new item uh try it out item id five so execute this we see it there if i add a queue here and execute it shows up now if i take the queue out of here and i put it in here let's see what fast api will do with this so q this is a query string execute this and it doesn't appear okay so i'm guessing it's using the the data model here um for a request body whereas like anything else will default to be part of the query string so let me see if they just did that yeah so uh function parameters that are declared to be pedantic models should be taken from the request body and then things that are just regular types are going to be interpreted as query parameters so it says that here okay and then if you don't want to use pydanic you can use body parameters but i'm not going to look at that because i want to follow the patterns of the framework how to think like a programmer uh you just have to like write a lot of code and learn a lot of things um if you learn one thing um i think it's gonna be difficult to think like a programmer because you won't really understand like the common things between languages and frameworks so you definitely want to learn more than one thing uh fast api is a web framework that focuses on apis um yeah so not valid because it's not part of a pythag model yeah so um that makes sense i can that's pretty convenient though considering like you can kind of map a json object that you would have in the body to a model uh qbasic you know i've never used qbasic um one of the first program languages that i ever used was something called pure basic uh this was maybe like 2004 um i wonder if it still exists let's see yeah it's still uh it's still around let's see if the website looks the same no it doesn't anymore but i remember like i i bought this like it wasn't free um like there was like a free version of it but if you wanted like the full version with like all the the library then uh you have to pay for it let's see if they still have that yeah so i paid like whatever the price for a single user was at the time and it was uh one of the first languages that i used uh so query parameters and string validations fast api allows you to declare additional information and validation for your parameters let's take a look at this example or this application as an example um so i've already done that even though it's optional it doesn't exceed a length of 50 characters we can do that so import query from fast api so let's go ahead and do that um and then inside of the query so let's see down here instead of uh being just none i can do query and then pass in none first and then max length if i can spell max length is going to be let's say 10 so i can test it and then if i try it what's the syntax error um oh i need a extra closing parenthesis all right so start the server and then um q can't be greater than 10 characters so um let's try let's try something longer than 10 characters and executes and i get an error saying limit value 10 okay so if i take away some of the characters then it works so that's pretty straightforward that's that's nice um additional validation i just looked at that one we can have a default value as well so the default here is none but if i replace it with something else i should get like you know let's say the default is anthony and then i uh i run this again and take away the query string then we see q is anthony okay so that's straightforward we can have a minimum length as well so this is really nice so execute so it's going to be optional but if i provide a value like a it's going to tell me that i have a minimum value so i need like abc and then it will work who remembers turbo pascal that's something i've never used i remember the name but i've never used it myself um you can have regular expressions as well so regex um let's see this is fix query and then let's make this 20 now and then if i execute it says it does not match the regex so if i change it to fix query and execute then it works so that makes sense default values i already did that with my name maker required so when we don't need to declare more validations or metadata we can make the q query parameter required just by not declaring a default value like this instead of that um but we are now declaring it with query for example like this so when you need to declare value as required while using query you can use three dots so i actually don't know what that means in python but if you want to make it required you would say q is a string and then use three dots and then if you hadn't seen that ellipsis before it's part of python and call ellipsis let's look this up really quick um that's not very helpful as a description but um yeah you kind of just skip over the default value so there's nothing there then we can use it so that's something i have to look more into but it makes sense how to use it so if you have a query parameter list or multiple values when you define a query parameter explicitly with query you can also declare it to receive a list of values or set in another way to receive multiple values for example to declare a query parameter queue that can appear multiple times in a url you can write um you can write that yes so you just pass it a list and yeah that makes sense okay so let's create an example with that so um gets we'll call this query test uh query test here and then we'll have q which is going to be a query oh it's going to be a string it's going to equal query and then um we'll we'll use their example so it's going to be optional and it's going to be a list of strings query none and then q is q and return query items okay let's take a look at this so query test name lists is not defined do i have to import this from anywhere yeah from typing import list okay so right now is null but if i do q more than one times so foo and then q again bar and then one more time q equals bass and then yeah it's uh lis uh it's an array in json i haven't written a single code whole summer feel very lost and ain't good developer what to do um you just have to write some code like you have to if you feel like uh the things that you want to make are just too much for you right now then you'll have to step back and do something a little simpler um and then from there like go more complicated but don't let like something that you want to do that's complicated stop you from working right now like it's a process um the things that you want to do today may not be within your ability but as long as you keep working at it eventually you'll get there so let's see making to-do lists or twitter clone is useless actually i don't think they're that useless so um they are useless in terms of like motivating you to do something but in terms of like the patterns for um learning programming or web development in general i think they're pretty useful because like the patterns are always going to be there like the idea is to focus more on like how to make something work instead of what you want to do whereas when you're doing something that has like a valid business case you're focusing on what you want to do and not how to do it because you should know how to do it already it's just a matter of writing code but if you're at the point where like you don't know exactly what code you need to write to have a certain feature then you need to step back and work on things simple like a to-do list or a twitter con so that's why like those tutorials everywhere because once you know like the patterns then you kind of adapt that to your uh your use case and you go from there but you definitely don't want to be in a position where like you're trying to learn like your business case and the programming language at the same time it just makes it so much more difficult but of course ultimately like you want to do something that has like business value or personal value or whatever so let's see more documentation so lists multiple values with defaults um let's see you can also use lists directly instead of list stir okay that makes sense all right i'm gonna skip over that that seems pretty simple um declare more metadata you can add more information about the parameter the information will be included in the generated open api and used by documentation user interfaces and external tools so if you add a title uh query string so for one of these i'll add that let's see title equals query string so if i go back to swagger and then i go to uh create new item so put requests and i look at it here in the documentation um where is it this one yeah i don't see i don't see my text query string let me try the other one redoc and i go to create a new item queue okay yeah so it says query shrink here so just uh just depends on the documentation that i'm using and they can do the same thing with the description and then we can have an alias so how does the alias work imagine that you want the parameter to be item query like in um football items but item query is not a valid python variable name okay okay so declare an alias so that makes sense and then just put it as um an alias and then deprecating you can put deprecated equals true okay so yeah i like i like all those features so let me see let me see how much documentation there is for this i want to i'm going to look at like database stuff um and i'll come back to like path parameters yeah because like a lot of this stuff is useful but it wouldn't apply in like every common case i want to see things that are more common so let's go down to the database stuff uh okay here okay so fast api doesn't require you to use the sql relational database but you can use any relational database that you want here's an example using sql alchemy you can use you can easily adapt it to any database supported by sql company like you know all those so there's an official project generator with fast api and postgres with docker okay so um fast api works with any database in any style library to talk to the database a common pattern is to use an orm an object relational mapping library an orm has tools to convert map between objects and code okay i know what rom is let me skip this part um for these examples let's say you have a directory name my super project that contains a subdirectory called sql app with a structure like this create the sql alchemy parts yeah let's do that so let's install it so pip install sql alchemy and let's just start writing the code right here um so from sql alchemy import crates engine uh okay so this is going to be like sqlite well db.sqlite3 so we'll create the engine um database uri i don't need any arguments for this and then um let's see session local equals session maker auto commits yeah i really don't need any of that either just bind the engine and then base is declarative base okay so all this is straightforward and then we can create a model so we'll call this um i'll just go with their example so table name is users and id is going to be and i need to import these so from sql alchemy import boolean column foreign key integer and string and also relationship and i'll just do a couple of columns so an integer column primary key is true index is true and then i'll have the email column so column it's going to be a string for this one unique is true we'll put an index on there as well i'm not going to create the item and then um don't care about the relationships okay so i want the pydanic models so you can go to schema we can create a user base um and like a user create so let's do that we'll have um class user create well actually user base we want user base base mod already have an email is a stir and then i really don't need user creates um and then class user so let's see we have the same name so we'll call this user model and this will be the user base and an id is an int and well really we don't need that either but we'll just add it so rm mode is true okay so let's see pidenix rm mode this is a lot to get it working so let me look up tortoise let me see what it looks like um so to clear the model like this and let's see because this is really tedious to get working like this isn't as um it's not as clean as the uh the rest of the framework so i mean this makes sense because sql alchemy is a separate library so you kind of have to work around it but i was hoping for something similar to like flasky guacame where it's kind of easy to get working and then use something like marshmallow it would be a lot easier than what's going on here so let's see if um let's see what else but i can always come back and follow this like let's see so crud i get users users okay so that makes sense just have to have different models i wanted to see like tortoise i thought it would be closely integrated with it try with mongodb yeah i think mongodb would be it'll be straightforward to use but at the same time you have to see how it kind of works with um with the pythanic models uh thanks for stopping by alpazian um thanks for being active in the chat as well why is it satisfying watching someone suffer you know i guess uh you know just to know that you're not the only one but yeah i was really hoping for something i was really integrated well so let's see today's orem and then fast api see anything like official yeah so let's let's look at this um so you create a model using tortoise and then pydentic meta and then yeah you create a model from this and then you have the tests you have main yeah so this was kind of what i was expecting like just looking at this um it's a lot easier to get set up like you create your model of course uh and this is in tortoise and then you uh just call this pythag model creator and it will create the model for you and then you can just start using it right away so like git users you can have user pidenic and then from query said users.all so yeah that makes sense so users.all will be a query on the user model and then you convert that to uh the return value using from query set which is automatically generated for you whereas in the example that they have here like if you go down to crud uh crud utils like the creates like create users see you have to add everything yourself which i mean it really isn't a big problem but you know what was so nice about fast api with all this stuff is like it kind of knows what you want because you're just doing something that's common and if you want to do something that's uncommon you have to add more onto it but you don't have to do all this code like because none of this code here for sql alchemy none of this is unusual like for any model that you create you're going to have something similar to this so like you'll just be writing the same code over and over again and you know the whole idea of fast api was um uh it kind of stops you from needing to do that um so what's the difference between fast api and flask um really i'd say like fast api is more modern looking at it like it takes advantage of more features of python to make things easier for you to work with by taking advantage of type annotations you can save on writing a lot of code because uh it can kind of interpret what you want to do from just those annotations i think we will finally see uh overlay on sql alchemy like in flask uh which will facilitate working with models and fast api yeah that would be really nice um or maybe someone will have to create it like let's say fast api sql alchemy like perhaps somebody already created this um yeah so like i see one here a simple integration between fast api and sql alchemy let's see um their example is not very good so i don't know i don't know it's not that popular of a library but also it's not async so um let's see uh i forgot for each syntax in google in front of an interview because i never use it um see how methods become async when use uh taurus or yeah so because tortoise is uh async like you have to use async for all of them so yeah that's uh that makes sense not just working with tables you work with relational data um breaking changes are expected yeah so um it is nice uh leverages flask and django features renzo asgi so it can be async as well yeah yeah and um it isn't necessarily a competitor more like a very good framework that combines a lot of good python features so uh yeah so let me think let me start thinking about like what i would want to have in a video for this because like where did i get down to i got down to um query parameters and string validations so let's see there's more validation stuff more parameters like let's see what this means update item okay yeah that makes sense um field to nested models extra example cookies headers response response status code what does this look like okay that's really what if you were to return a certain status code oh okay you just put it there i guess that's if it's successful uh form data uh it's a typical api i wouldn't focus on form data request files handling errors okay so yeah i think i think i know enough of the basics so basically you know the idea of you have um incoming data you have out your outgoing data uh yeah so i think for the video i'll make an example api so let's make that example api now like uh what do you guys would think would be a good example for an api so i remember like one of my very first videos on the channel was my example api was like languages so basically there was like an in-memory database where you can add like programming languages to it and um you would use the api to interact with it so you can view all the languages in this in-memory database you can add to it you can update it and you can delete things so i want to do the same thing in fast api but with a different example so do you guys have any ideas on the example i can create i'll create that in the videos the last thing i'll do here and then i'll create an actual video uh for it so what do you guys think so actually i'll close this i'll make a new one it's not flask um pip install fast api and hyper corn uh am i good with bash script i haven't written any bash scripts in so long so i can't say i'm good at it async is the future it's not that easy converting o libraries like flask yeah this is such a different way of doing things that um you know i can see how old frameworks can't easily be converted i know django wants to do some stuff with async but we'll see we'll see how that goes um a simple api where you pass the city and you get a local time for that city easy for everybody to follow along okay i'll do that one well i mean that city okay how about this so um the the api will allow you to like add and remove cities from like an in-memory database and then like when you get all the items or you get like a specific city in addition to the name of the city it will show you like the local time the reason why is because um i want to show the different crud operations if i only showed the time then that would only be git but if i make it like around cities then i can uh show like create read update and delete so we're gonna do that one so um we're gonna create a file called main dot pi and uh we'll say from fast api import fast api app equals fast api and we'll create the uh endpoints so we have a git um we'll have so it'll be city right should be city or cities let's do cities okay so this will be uh get cities um and then we'll just test this momentarily so we'll have git and we'll have posts uh posts cities and then return so i'm just putting these as placeholders and then uh put cities so this will allow you to update a city i don't exactly know how that will work but we'll see all right well let's skip put because yeah i don't know how you update a city so we'll have delete like there's nothing to update if you're just passing in names so uh delete cities how about this delete city create city and then we'll have one for um cities and then um city city id city name we'll do city name now let's do city id well we can always come back to this it's not really a big deal so um git city and then we're going to have the city id here which is going to be an integer um and it's going to be required and then we'll return city and city every time i write like the same word over and over again i start thinking that i'm misspelling it does that happen to you guys like looking at cities now like it just doesn't look right like it doesn't look like it's spelled correctly like it almost doesn't look like a word anymore and so that's always weird like when i just write the same thing over and over again um all right so what i want to do is i want to create like uh uh create a model for the cities so i already forgot the name of like the pidanic stuff that i have to use so i can just look at this um where was it base model so from pydank import base model and then i'll have a city class and it's going to use the base model and it's going to have a name that is a stir right and then also it's going to have like a local time right so local well we'll come back to that i might need to put a time there but we'll we'll see how it goes um i think yeah i think on either time so i'll put time and then i want this to be um a date time so from date time import date time right so let me just look at this i need to see the type so from daytime import date time type of date time no so that's not what i want i want like a date time type so like if i do a type of date time dot now uh it's a daytime right so how well i think that's fine right so if i do this we'll see i think it's going to be fine but i'm not sure um so we have the time here so uh for adding to the database so we're going to create like an in-memory database so we'll call this um you know db and it's going to be an empty list and to start we'll have like examples of what it's supposed to look like so we'll have a name and then i'm in las vegas so we'll put that and then um it's going to have a time for now the time will be hard coded but at the end i'll use some kind of api or something to get the actual local time or just use daytime i don't know i'll figure it out but um let's see name las vegas and then the time is going to be let's just say 4 p.m but like i said this is just temporary this is going to change and i'll put a second one in here as well so let's try uh miami and then the second one will be 7 p.m okay so now what i wanted to do is i want to get i want to get all the items in the the uh the fake database so how could i do that so what i want to do is i want to return like well let's see it can it be this simple so let's see hyper corn um main app reload and then syntax air delete city okay so let's go to um port 8000 do cities okay yeah so that works so it's doing the conversion for me i have this list here and um it's looking in a fake database here so uh las vegas time 4 p.m 7 p.m okay so that all makes sense if i want to get a specific city city id so what i'll do is i'll add ids here as well so add id this will be id 1 and this will be id two and you know thinking about i don't think i need like actual ids i'll just use it as an index so like for this i'll say return db and then return the index of the city id um minus one right because it's zero index so now if i go to like cities slash one i get las vegas city slash two i get miami and city stat3 i get an error of course but um one and two are what i want and then uh let's see creating a city we'll just be adding things into the database so creating the city i need to take in the um the city here as um an option so we'll say city and then it's going to be the city model here so it should be in the request body so let me go to swagger and then i can post create a city and uh it should allow me to create it with um a daytime so a new city would be like london and then i don't know what time it is in london let's say well let's just keep it as 23. and um you know once i get that city i have to add it to the fake database so i'll just append it it has to be a dictionary so i'll take the city and then i'll just call on it and then append it to the database and then i'll just return the index of it so um return uh db minus one let's get the doesn't have a colon uh just minus one and it will give me the thing that i just added so let's see if that works well so i add a new city i'm to add london execute and then um we see london is the response so now if i go to cities and try this out and get all the cities we see um london is in the list uh since i haven't restarted the server like this persists so deleting a city deleting a city i need the id again so city id city id uh it's going to be an integer and then what i want to do is i want to uh i think it's pop right um let's see stop the server um let's see help uh list stop pop and yeah it's the index okay so uh db.pop and then we want to pop the index of the city id minus one so um city id minus one and then return a status code so i think the status code goes here so i was just looking at that in the documentation but i forgot what it is already so let me go back status codes where response status code you put it in the uh the decorator so status code should be 20 not 201 204 and let's see so 204 hour turn and then import status so status and then um this should have status code equal status dots it's not appearing in my editor let's see http 201 um no you know what i'll just return it directly it's probably no content but i'll just put 204 okay so pop that and how to return like nothing just an empty dictionary right so let me start up the server and refresh the page so if i go to get cities and execute well create cities it just added london if i do get cities i have las vegas miami and london so if i go down to delete a city i want to delete um did i put the oh i forgot the part and the parameter the path so city id have i imported status yeah i imported status so let's try this okay so i want to delete well let's see get cities first so we have las vegas in miami i want to delete miami so that would be number two execute and we have successful response doesn't return anything because um well yeah just making sure it's it's successful like it's red for delete i'm thinking like red is an error so if we go back here to um execute i'm expecting that miami should be gone and it is so we only see las vegas so um it looks like everything is working so now the the the hard part is like getting the time of a particular place um i'll need an api for that but like how do i make this optional or not even optional just like hidden like it's not something that the user would do so let's see um so let's look at fields and then it's not quite optional it should be like completely hidden so like i feel like i saw that somewhere like when i was working on the example like i'll go back to the main page so let's see like the the thing with the taxes so maybe that was the main tutorial um request body so we have the optional ones like the one where it adds the the tax okay so no this isn't quite it would be the best way to do this well really the time isn't necessarily a part of the model itself i can set the the time is something that um it's kind of like a an extra property that they have but it's not necessarily on the model so maybe i should put it somewhere else so like i'm thinking here like when i return the values like before instead of just returning the database so i have to loop through and like update each one of these with the actual time from that city so let's try that so um for for location in db what i want to do is this so results will be an empty list so for each result in the database i'm going to loop over it and we'll say results.append and then we'll have the name we'll have the name be location name and then we'll have the time be something so time will be like you know um 4 p.m and then return that and then let's see so now if i run this and get all cities execute uh we have 4 p.m if i try another time just to make sure it's working so 2 p.m um yeah so this is where it would be um and then i can do the the the call here don't you like comprehensions uh yeah comprehensions are fine it just won't work here because i'm going to add the code to actually determine the time so like um you know let's see local time api so let's see does this return the time i don't want the time zone turn locations okay return time so this it's gonna look like this a little bit so uh import requests and then um it's not there so pip install requests so requests dot get this and i think i should store the time zone first yeah i'll store the time zone and then i'll uh i'll get it so like when when they're created how about this so time zone and then this will be optional so from typing import optional this will be an optional string that defaults to none okay so now i know what to do um i'm going to get the time zone from here so make this an f string let's make this single quotes um so this is going to be the thing that is variable so we'll have the location time zone right and let me just put that one back so europe slash london as so time zone then we'll have uh europe slash london for both and obviously these will change but i just want to test out the api first so europe slash london and then the location goes in there um and let's see we want the time so uh we'll have the time zone first and the uh location time zone and then we have the actual time which will come from the response so first we need to see what the response is i don't think it's jase get json it's just json okay so let's let's run this so response equals requests url json yeah i don't want to i don't want to return the uh entire response like i just don't want to like add it to uh my data structure here so it's going to have name time zone and time because i'm sure that this will have more so i messed this up this should have double quotes and then uh we'll see so i want to get all the cities first and they return an error so key error time zone um so location in db oh this one doesn't have a time zone so i'll add it to this one okay and restart the server if i can okay all right so it looks like it's returning uh everything correctly and then it's getting the actual time so let's see the abbreviation the date time uh the day of year let's just use date time right so yeah uh our json here and then we're going to get the date time just like that so let's try this and execute it okay so we see the uh the date time in london right now so now we need to store the the the real date time uh hey coco welcome to the stream um we need to store the real date time so this won't be so this well what's the uh what's the time zone for las vegas um america chicago that's not my time zone and i don't have a vpn running so that's kind of weird um okay a list of valid time zones so america i think it's los angeles yeah so america los angeles and then um for miami is there one in miami or let's see i mean i can use like new york city or new york so take that and add it to miami okay so now when i run this now when i run this um i can execute and i should get two different times so uh in las vegas is 1659 so almost 5 p.m and then in miami is three hours later so that works so now i want to be able to determine the i want to determine the uh the time zone depending on the city that the user inserts i really like f strings many people still use the ozone string for matters i don't know why it's like the old scale old school like c yeah i like f strings as well uh pst yeah i have to use the time zones that come with this so i don't think it uses like um you know like pst or you know bsd uh but maybe like i see me t um but no i don't see like psd so you have to use the um i have to use one of these even though i see est well i know there's like p dt i think but yeah it really doesn't matter like uh i just need to use one of these uh time zones for it to work so request a list of valid locations for an area okay so the area what would the area be europe um location so like i don't know how i can determine the i don't know how i can determine the area like i know how to get the city but like if someone puts in like london like how do i know that i should be looking in europe instead of america so like one thing i can do is i can make it to where um i can make it to where the user passes in the time zone i mean that'll work because i don't want to do something where like i have to bring in another api just to find out where a city is like i don't want to get that complicated so yeah i'll let the user type in a time zone so we'll go here and the time zone will no longer be optional so it's going to be a string and then yeah so let's see let's try this out so we're going to create a city and we'll we need to refresh uh get all the lists and then search for the cities and lists well the problem is like it requires the the area first so like the continent first so um like i can't search that way like starting from a city i won't be able to i mean i could like perform a request on like each continent but that doesn't seem like the best way to do it so let's see create a city i'll just pick a time zone uh anchorage so yeah i'll put anchorage in there so try try it out so timezone will be america anchorage and then anchorage will be the city execute it was added now if i go to get cities and try to sell and execute now i see in anchorage right now is 1603 so it's an hour it's an hour behind my time and now let me add one more let's try a different continent uh asia toblesi see go to here to asia to blissey add sublisi and execute and it's in the database now and now if i get all the cities we see in tbilisi it is currently um the next day so it is september 3rd in tbilisi and it's 403 am so um it's new scene types what is that called uh just in general in python like it's called type annotations um but for fast api like it uses like fast api or it uses type annotations for fast api internally so you can't really use fast api without using uh type annotations i mean fetch the time zone list and then search the city and that name a list oh that wouldn't work either so like the time zone um names are based off like a main city so like for instance like las vegas the the time zone is america los angeles because like it's in the same time zone as los angeles but like you can't search here for los angeles like i mean you can't search for las vegas like they're only 386. um so they just pick like a main city in like a country or whatever and then that time zone is like the base for other cities in the in the area um it'd be too much work well like working with this it's really nice um like you just have to get used to it but it's not really more work like in the end it's actually less work it's more powerful than writing everything yourself because fast api is able to kind of determine what you're trying to do so um i think this is it for the api right like are there any other features that i that i must uh add must be a geolocation-based solution yeah there are definitely ways to take a city and then search for like its time zone and its country and everything like i've done that before it's just like i search google for the first time api that i've found and that's just the way it works like i can always change it but like i really don't think that's a big deal like i just want to demonstrate the api so um are there any other things you think i should cover here or would that be it like after this i'm going to kind of go over this to make sure like this is the best pattern i'll see if there's like a async request library so i can use that instead of requests to kind of get you know all the value out of it but uh this is like the basic thing that i'm trying to do so uh anything else that you guys can think of like how long have i been streaming i have been live for two hours and 45 minutes good night thanks for thanks for showing up to the stream it's probably good timing because i'm about to end the stream if nobody has any suggestions so yeah like i was saying at the beginning of the video um i'm going to create like this again probably more like uh you know more polish and i'll create a video for it um you like the docs page for flask use postman that is a plus for fast pr yeah like that's really convenient that that's working right out of the box um wsl 2 is pretty good for python there are some issues like i couldn't install uv corn earlier so it's not perfect but it works it works pretty well so i guess that's it um this is my second stream this week what i'm gonna do is i'm gonna try to um stream more and you guys can join me and you know we can learn some other things together and maybe create some more example apps but uh this has been a really good stream i learned a new framework and uh i really like it i think i'm gonna use this going forward in the future i'm going to learn more about how it works so um yeah thank you for coming and i hope to see you guys soon and talk to you guys soon
Info
Channel: Pretty Printed
Views: 23,218
Rating: 4.9320755 out of 5
Keywords:
Id: GSMYt429ot4
Channel Id: undefined
Length: 166min 10sec (9970 seconds)
Published: Wed Sep 02 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.