Let's Build a Fast, Modern Python API with FastAPI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone and welcome to today's webinar organized by jetbrains i'm paul everett pie charm developer advocate and i'll be your host the topic for today's webinar let's build a fast modern python api with fast api today we have michael kennedy founder of talk python training host of the talk python to me podcast co-host with brian aachen of the python bytes podcast co-author with matt harrison of the effect of pycharm book all-around lovely human being welcome michael well paul thank you for having me here it's always great to be on the pycharm stream now it has been just the webcast but you guys are live streaming how exciting yeah in fact you have walked right into my prepared ad-lib number one you're a long-time friend of the webinar i believe this is number six want to take a guess at what year was your first one oh i guess oh my god yeah 2018 [Laughter] off by four years what your first webinar with my charm was 22 months before i joined jetbrains wow how about that that's incredible speaking of which you recently you the royal you talk python talk python2 podcast recently passed a significant podcast milestone share that milestone with us along with your current rank as a technical or developer podcast yeah well thank you so i've been doing the talk python to me podcast for about as long as i guess i've been doing jetbrains webcasts and you know it's i i was looking through the numbers of downloads and stuff recently and i just realized we passed 20 million downloads for people listening to the show and at least according to the itunes charts which a lot of the different things like overcast and other players pull from we're the number two in the world developer podcast those javascript those pesky javascript people are beating me but yeah i'm the best barbarian i'm on their heels we're gonna we're gonna get there yeah okay let's talk uh fast api for rest endpoints um you have a brand new talk python training course is that right i do just came out recently it did i'd say it came out about three weeks ago actually and i'm really excited like i've been waiting for something like this to catch fire not the course but the technology yeah you know so that's that's kind of my question is tell us about the course but also tell us how it got on your radar yeah uh radar and then course i think makes the most sense so what what i've been wanting is a modern python web framework i mean all respect to django to flash a lot of my stuff's built in pyramid i like all of those frameworks but what i want to be able to do is write def async some method use type hints in a way that are meaningful and write modern python code that you know tooling that honestly like pycharm brings together that really just makes that experience feel like the best that it can be with all the cool features of python and i looked at japronto i looked at sanic i looked at a bunch of these things and they all seemed to spike and then drop and turn like oh this is amazing but it's not amazing in some ways or it's amazing but it doesn't work on windows or whatever and you know fast api seems to be the one that really has the the traction around this kind of stuff and it's it's been around a little over a year and a half there's a hilarious joke that sebastian ramirez the creator of fast api put onto twitter there's apparently a job posting saying you have to have four years of experience with fast api he said well i can't apply for it i've only i only created it a year and a half ago so that's all the experience i got right so anyway that i've been waiting for something like that and now that that's both come along and seems to have legitimate traction i'm like all right now how do i you know i was super excited about how do i spread that joy well let me create a class and show other people how neat it can be and you said experience and i think that's part of the reason it's gotten meteor meteoric rise is it just the here's a pile of code you go to the website it explains what it is explains why you should care and then documents the crap out of it and has batteries included for everything right yeah it's it's really really neat and it's called fast api but what's interesting is it has all the mechanisms and capabilities to be on par with flask or django or pyramid in that it can be it renders tips templates dynamic templates like jinja or i added chameleon recently as an open source project extension and it does static files and all those kinds of things but you know better yep and you don't have to assemble a bunch of half-maintained add-ons right yes exactly all right okay uh very good let's have some fun um get back to getting started for the webinar all right we'd like to make this webinar as conversational and live as possible so should you have any questions or problems during the webinar feel free to ask them if it's that way or that way but ask them at any time during the presentation using the chat in youtube i'm looking over at it right now we'll have a few pauses during the webinar where michael will answer your questions i will answer some of the questions as well right there in the youtube chat if they're really hard questions i'll save them for michael uh who will pause every now and then and say hey paul you got any questions please don't wait until the end of the talk ask your questions as soon as you have them usually the most common question is is this thing being recorded this used to be funny when it was go to webinar a couple months ago and i'd always joke that in five minutes we're going to have someone ask is this thing being recorded it happened every time for the last four years i've done 20 30 webinars well it's not funny anymore because of course it's being recorded it's youtube so it'll be available immediately at the end of this basically um all right so now that we're all set michael give us a walk through a fast api over to you all right sounds good well uh can you guys throw my screen up yeah let's let's do that so i i gave you a little bit of an introduction to fast api why i thought it was neat and powerful right it's it brings together all these cool features of what i consider modern python that's async and await that's type hints that's python36 and above so f strings all those kinds of things yeah so uh can you focus switch over my screen flip that on and then i will show you so i'll give you all who are watching just the quick run now we're going to talk real briefly about fast api and then we're going to build a real simple little like hello world api and then what we're going to do is we're going to interact with some live data some live external apis kind of a mashup type of thing our api is going to consume other apis that is going to um that's what we're going to ultimately build yeah hold on sorry yeah yeah how's it going over there guys i see my screen but i know it's not in the stream okay it says that we're sharing your browser right now yeah can you see it all right now here we go now it's in the stream okay perfect so welcome to fast api you know this is a great framework that sebastian ramirez has created as i already said so if you go over there documentation is great the website is great i'd like to call your attention to the top right small it might be hard to read so 24 000 stars you might think well michael if i go to django they have 50 000 stars and if i go to flask it has 51 000 stars or approximately right i'm not pulling it up now well those are 10 years old this is a year and a half old the the the energy around this framework in particular as i said before is really really high so you can find fast ip api over here or you can pip install fast api the reason i'm excited about it as i said is it has all the it takes advantage and brings in all these modern features type hints async and await asgi servers you've all heard of whiskey wsgi web service gateway interface servers that's how all the python frameworks have interchangeable backend g unicorn uv acorn type servers those don't work for async and await so you need an asynchronous survey server gateway interface so you'll see that there's a very nice one associated with it here data classes and pedantic those are really nice ways to exchange and validate data if you want documentation what you do is you write a function that is an api then it is documented automatically that's really nice it has really interesting ways of testing with pi test and rich editor read pycharm support partly because there's a cool plug-in for pycharm partly because of item number one here type hints one of the reasons i like thai pens more than anything is they make the editors come alive right paul i mean that's that's one of the beauties is it knows what you're doing and the editors can help you indeed and this is something i want to follow up with you a little bit about later this is a you said modern yeah uh as one of the things that attracted you and this is like showcase number two after async i think this is the modern yeah that i totally agree with that you know pedantic is a little in there but like pedantics it's hard to disentangle that from typins all right so what to build i'm sure you all are dialing in connecting from wherever in the world it may be beautiful like over here in the mountains like where paul is it may be super wet in the pacific northwest where i am and if you're going to go outside you might want to know do you need an umbrella yes or no so our goal during this webcast is to write an api that you enter a location it will tell you umbrella yes or no okay but it will use live data and it'll determine if it's raining now it's not going to use a forecast it's more like if i'm going to go in the next 10 minutes not not if i'm gonna go out forever maybe we could build a little iot thing and it just is like e-ink and it sits on our desk and it just shows an umbrella or a hat you know that that's it and it just constantly updates we're gonna build the back end to something like that and are we gonna use real data yeah i built this thing over here at weather.python.fm that returns actual weather data like real weather data so in portland well let's see we were in new york and why the weather would be right now apparently it's clear but quite chilly so we're going to work with this api and basically consume this api in our api to answer the question of whether or not you need an umbrella so let's just see really quickly what does a minimal fast api api look like and then we'll go build that and maybe take some questions if there are any so you've seen this with flask and it's i find it interesting that a lot of the modern modern let's say just newish modern ah doesn't really matter the newish apis so many of them adapt they adopt something that is flask like but not necessarily flask where you create a thing the thing also has decorators and then you sort of call run on it right responders like that flask obviously a bunch of the others and this is kind of like that but not exactly a little more api-ish so we're increasing you could call it an app but if you're creating an api i feel like api might be better you write a function it can be asynchronous or not and it'll do either and you say api dot instead of route like you would in flask you speak in http verbs you can do a route and do multiple verbs and so on but here you say dot get the url and then you don't call api.run use an asgi server uv acorn which is a fantastic production ready server that you can use so this is an entire application i wouldn't recommend structuring it like this necessarily for a large one but for a small one this kind of shows what's involved paul any questions quite a few um some a mixture of high level and low levels so i'll start with kind of a high level one there was a question about django and kind of a common pattern in things that you do with django multi applications and e-commerce systems and stuff like that is it logical you think to try and do something like this with fast api i mean kind of brings in the whole server-side rendering templating question as well as being just an endpoint sure uh yeah it's pretty straightforward it's kind of like kind of like flask and that you kind of just render it you say i'm gonna render a template in code for the the template side i think it's it makes sense i believe i've never tried this so i don't remember exactly how it goes but i believe you can mount sub whiskey applications ah i think so i think you can say here's a whiskey app and route like slash blog to this flask sub piece or something along those lines i'm not entirely sure but i think it works that way some of you in chat that might have we have we have some superstars in chat so some of you if you've done this follow up and give a better answer on that yeah um going down a little bit further i'll say the magic words for you as a person uh nosql um and also migration tools things that you get from the big frameworks sure you get them here as well you just get them somewhere else right so uh mongodb certainly uh you could talk to mongodb with this you would use um you know something like engine or i think micro or tiny u i think it is for the async support there's also motor that comes from the the mongodb people that is the official async driver of mongodb all right so a lot of those plug in in terms of migrations i mean you don't really have migrations in but in sql alchemy you do and i would just use alembic so sql alchemy plus alembic okay plus fast api and i believe in 1.4 they're working on an async version of sql output as well all right cool and for those of you not doing nosql that might be using postgres or something there's that blazingly fast yes async yeah yeah there's an async postgres driver package as well and you know any chance you get to use an async thing if you can just type the word async here and then a wait on your thing and all of a sudden you get a hundred times scalability like that's the thing you probably want to type so you know when you're evaluating these external frameworks you bring in you know if they're all things being equal there's an async one choose that okay last question for now um this gets low-level dorky dork uh as far as alternatives for the loop um or the server uh uv i don't know if i'm gonna pronounce it right uv corn and g unicorn um what what what out of the box the fast api come with what alternatives does it support and i'm particularly interested on the uv corn because i believe that's an http 2 alternative uv acorn is not http 2 which is sad however i'm not sure it matters let me explain a couple things one uv corn doesn't come out of the box you gotta pip install it with it and there's no way to say api dot run if you go over here so awesome asgi do a little magic sorry to take you on a detour yeah no no it's cool this was the first question that was asked so if you come down here to servers here's the the story of the the ones at least according to this awesome list right i mean it may not be extensive so this one is really nice but it supports http one there's hyper corn and there's daphne hyper corn that's one yeah sorry yeah this one also supports websockets and i said i don't think it matters and yeah why do i say i don't think it matters whether it does because typically the deployment looks like engine x then a corn and then uv acorn worker processes sure and so the http one i'm sorry the htp2 i believe would be handled by engine x i'm not 100 sure about that but i think so so a lot of those things you know like for example you can serve static files for development but you should really just serve them out of engine x and never touch touch fast api at all or doing the production side where it really matters i think you would not let it get that far but if you wanted to just directly deploy this like you know having a cp2 here might be cool thank you for bringing this screen up just independent of fast api there are things going on in python land for web stuff and it's a little bit under the radar and that page lists a bunch of the things that could be important for people trying to do modern web on python we're going to be working with that in a minute as well okay all right we're back to you yeah okay back to me perfect i think it's time to build so you know i know if you guys saw this article i think it was about a year ago by mark andreessen called it's time to build it's actually not quite a year ago the beginning of the pandemic what a neat article uh hopefully you guys are going to build something awesome with this knowledge afterwards so let's just go and build something here huh paul all right i made my screen small and it ginormousized my pie charm so what i'm going to do oh by the way is this on the m1 this is this is on the m1 how about that huh yeah so this is my mac mini m1 with 16 gigs ram so we actually did a fun live stream last week exploring this for python for example there's weird things like you have a terminal and you have a rosetta terminal because sometimes you need to install stuff that depends on the say intel platform wheels of python and we're going to go down that route this way this time as well so i'm just going to go to my desktop make an umbrella folder i'm going to create a virtual environment and this is everyone should do this everyone should have one of these i have a thing that creates a virtual environment activates it and then makes sure it has the latest pip because do you know what happens about 95 of the time oh through spread out throughout the year when you pip install or you create a new virtual environment and you try to pip install something it tells you it's out of date so just update it every time i wish python did this on its own okay anyway so it is and then we're gonna have a main.pi in here and let's go ahead a requirement stop hi and then let's open this over here into our lovely pycharm okay it's coming to life it may decide there's an interpreter let's see it has found the umbrella fantastic it's a new new sort of auto detecting thing in the latest release i think and it knows the virtual environment should be ignored which is pretty sweet let's go ahead and run this and make sure that we're capable of running nothing fantastic we are we're running on python 391 i believe uh did i name it that paul how do you let me put that extension on there all right so in this thing we're going to have a fast api and we're also going to need uv acorn like you saw there's other options so let's install those requirements all right now pycharm does think those are misspelled but you know what i happen to know they are not misspelled so we're going to tell them it's not all right that's great now let's just do really quickly let's bust out that that example so import fast api import uv acorn api equals fast api see how fast that type hints work it's so it's like gosh it's like a joy okay uh we do a get to uh slash and we'll do slasher now def index um we're going to return some data this will be message it's going to be hello world and the status i'm just making up stuff at this point is okay yep whoops and then what i'm going to do is i i wanted when i first started this framework i wanted to say run and it didn't like it so what i found was there's no built-in run but i can uv accord and run the api all right run it and look at that we have our api built so part of the word part of the name of fast api is not that the apis themselves are fast however if we look you'll see that it is one of the fastest python web frameworks available on par with node.js and go which is fantastic but the other part of fast api is i can build an api quickly at the fast applies to the developer speed not the execution speed right okay so this is our our simple example but let's let's go and make this a little more realistic okay all right so maybe i'll save this for you i'll call this main hello not hacker hello regular hello and we're going to evolve this one and i'll just leave that one there for you all okay so this one what we're going to do is this little jam everything into one file world this is fine for documentation this is fine for a cool little 25 minute python presentation but for a real app you're going to be hating life if you put everything into one file right so let's do this let's do a little organization here we're going to create a directory called api we're going to create a directory called views we're going to create a directory let's go with that for now and over here i'll just this is going to be where i'm going to put my random stuff out of home views and over here i'm going to have let's call it a a weather api or something like that yeah sounds good yeah yeah cool so what i want to do is i want to take this and i want to put it over into the home and in fact let's do notice there's a problem we got to fix this in a second fast api and say from fast api import is it ginger template autocomplete man i know i know i know there we go so i think i'll just do it like this this is not something i use that often because i have in my opinion something better that i use but nonetheless this is how it works uh i think you're like this equals uh templates yeah like that then down here i can say return templates dot template response and then what do we put in here the name is going to be index.html and well that's a good spelling html and then the dictionary here the context we're going to need to pass over a response a request this is needed this is needed by underlying jinja so we're going to have to get this to come over and how do you do it well now comes part of the type and stuff so what you do is you come over here and say this thing takes a request well what's fast api supposed to do with that is it because it's name that no you come over here and say it's a request object and you import that first oh i love this and it sees oh there's an object or a parameter and it's of type requests i have one of those here you go isn't that sweet i'm not a fan of magic names magic order yeah you call this whatever you want and it'll be fine right yeah exactly really really nice but you can see it's not loving this so what we need to do is we need to come over here and say we have a bloop but not a blueprint a route a router blueprint would be the flask equivalent it's a fast api dot api router and what does it take think we need to pass anything to it and this lets us break up like we define all the routes and then we say hey api thing here's a few more that we got from somewhere else and towards the question of how do i partition this into like little sub apps you could build a package that uses the router and then use the router to plug in that that part of the application in so that's pretty cool that actually looks like something the little pie charm elves could speed up a little bit right and they sure could some kind of intention to generate that yeah exactly decorator yeah that'd be sweet wouldn't it okay uh this is not listed in the requirements but it's a dependency but let's go ahead and let pycharm add it to the requirements for us and there we go all right now this if we run it let's try to run it it's probably going to be hating on it well there's a couple of things one it's not found so what we got to do is we got to go back here to our main and add those back in so i need to go let's see this let's do configure say api dot include router and let's say from views import home and down here we can just say home dot router and we want to make sure we call this configure thing for now but we only want to do this in development but not in production so let's do it like this use a little live template how about that um maybe like this keeping it short okay now let's see if it works again so here's something that you'll run into with fast api as you work with these sort of extended features you have to install more dependencies so for example if i want to use ginger templates i gotta install ginger too if i want to serve static files i gotta include aio files which is an async i o files thing yeah so let's go quick throw that in here install those wait a moment and when we're ready we'll run again okay off it goes now it's happy uh one more thing let's go ahead and add those templates templates what i call it and we'll create an html file called uh index and this will be uh um umbrella h1 umbrella one more time umbrella okay so we've got our our umbrella thing right we've sort of even added this whole hey it's a whole web framework you know not just apis right well so that's pretty neat now let's do let's go over to our weather api and let's actually start focusing on really building this api this is what we're actually trying to build but something that that can sort of be driving you crazy is if you don't put some kind of home landing page basically every request starts with not found 404 what do you want to type now so so that's a little funky so i would say you know i always kind of start by having this and i wanted to show this to you because you know once you're down this path right you're pretty much ready to write like replace flask or something like that with just a little bit of effort okay i'm glad you're showing this because i think most people think a fast api is api and that i've got it's only usable if i've got a javascript single page application in front but that's not the case you can do the server-side rendering part yeah in fact you you probably could use chameleon as a templating link why is this not showing up i could i could so i also added this is sort of two things in one i also added a decorator where if you want you can just put a chameleon decorator on there and then someone else i forgot their name i'll see really quick also created a ginger one so there's a like a friendlier decorator style so here you just put fast api ginger on there as well so anyway i think those are neat ways to work with it now let's go over here and build do i but maybe not capital i need an umbrella now let's see this is probably going to require a city which is a string it's going to require a state potentially which is an optional string because if you're in a place that doesn't necessarily use this concept of states which could be none and it's going to require a country which is a string but we could give it a default um i'll give it a default us potentially just to show you can have a default that happens to be where i am right this is pretty cool yeah paul we can do this and actually if we add this to our fast api bits you'll see that it's going to use that stuff so if i said like city was an integer like it's a city code or something if i pass in a string that is parsable to an integer fast api will turn into an integer and i just get it as an integer yeah using standard syntax standard names of built-in types and and if we have time later to get into my little hobby horse about static analysis this then feeds into the entire universe of other python tooling it isn't some stove piped only works with django model config syntax i will complain to you pie charm will give you red squigglies and things exactly it's fantastic it's fantastic but let's go first of all we're going to need our route so let's put this back it's not actually an end let's go router equals fast api dot api router at router and this could be a get or it could be a post or whatever you want and we're going to say this is going to be api umbrella no give me just a second there so what we could do is we could let's just return just the city for just a second okay and we're gonna need to include this router and all the other routers it might have so what do we call it weather api by charm help me thank you look at that okay so we're going to include this and actually let's go to our uh template and that's even to help high charm this is a template director says oh do you want help we have no idea what language you like well i like chameleon but what i'm going to tell it nonetheless is the template language where are you not there there it's hiding the bottom i want this to be ginger and so now it'll give me auto complete for like the jinja semantics okay so i could even come down here and say slash api slash weather uh no umbrella that's what i said question mark city equals portland and this just will give us a nice little way to test this so we click on this does it work yes look at that so now we got our city pass through but watch what happens if i omit it city is required it's a strong type not an optional type and it doesn't have a default value so it's required that's part of my api as the function call so why is that not part of the api as just consuming it isn't that cool yeah so super super neat let's go over here and do one more thing i think we've got time to make this happen let's go and define like we could have this and this is all well and good but let's do something a little bit nicer let's take advantage of some of the pedantic stuff i'm going to come over and create a models folder and into the models folder i'm going to create a location class location now this is a regular class and it might have a city which is a city which is a string it might have a i'll just nab those from over here so they're the same is this the pedantic part what yes of course it is and we might have a state and at this point we can swap their order and we can you know what i really really wish i love python but i wish it had this like uh c sharp does come on i'm sure they did you'll get you'll get a vertical bracket to replace union in 3.10 but they should no cut down yeah yeah i just don't like that i have to import it i don't like it it does the same thing yeah it's it's really clever okay um so if we had this it'd be cool to say well we can take a location wouldn't it if we just said you know this is the location that's sweet location is one of these and we gotta of course import that oh no stop i didn't mean it import that and then we just return our location it knows how to convert that to a dictionary except for it doesn't love it it says this thing is not a valid pedantic field right so what it needs is it needs this to derive from a certain base class say this is a base model from pedantic it says pedantic is not in your requirements but it's a dependency it's like indirectly there so nonetheless i'll get put it there now it's great it's almost great it seems like oh this is going to work yes umbrella no that pedantic thing only works when it's doing a post and that value those values are coming from the body i wanted to come from the query string i wanted to come from like if i had just slash portland like this sadly no so we can use a almost everything i love about fast api this is just weird but what i can use is i can use dependency injection to get the variable from the query string and i can say this is a fast api dot depends that means go look somewhere else i guess it's sort of the thinking to me that's that's a bizarro thing this dependency injection seems like something else but nonetheless there we are look at that we've got portland which we specified we got state which we didn't but that was fine in the u.s which is required sorry this country which is u.s is required but that's the default from the model what do you think paul lots of things to say on this all right you wanna i think we we probably got time to say something real quick if you like um i have a big pile of questions i don't think you want those yet do you want them yet we are close close close to umbrella yes or no so let's let's hold off on that really quick and let's just so i can wrap it up and then we can just free freestyle a little bit yeah sure all right so the last thing we need to do is like this is cool i built an api that echoes it echoes out what i sent into it something else is cool honestly check this out docs uh spelling of docs is super hard but i'm gonna get there eventually check this out i've got an api it has two methods one the index wait the index yeah the index that's bizarre uh hold on so let's go back and fix that right uh we don't want that i wanted you to see that over there but i don't really want it i can say include in schema is false this is not an api method this is some other thing that i'm using okay so if i rerun that okay now we just have the am i do i need an umbrella look how it like named it that's kind of sweet so if i say get it says city country and the response type is we have no idea that's a bummer but there is an id it actually has an idea um response model is location see that now that's not what it's going to be in the end but it what it is at the moment so if i come back here and i refresh check it out there's the schema on the response type as well so let's go and create one more model so i can sort of keep rolling with that and i just have to delete it uh we're going to have one more class it's going to be um marilla status i don't know class umbrella status base model it's going to have a need bring umbrella which is a bool it's going to require that we have that value and we're going to have a temp which is a float like that and we'll return those things actually from our model so we can set that there the final thing to do is to implement this right so let's go over here and it seems might get like it might get tricky or hard but we're pretty close url is going to be let's go over my whole lot of stuff going on up here that i don't need one of these there we are and let's just make them go away okay so we want this so the city is going to be something the state is going to be something and the country is going to be something and paul you're a fan of uh f strings quite a fan and you know there's this little ide that makes them all magical for you they will actually give you an intention to convert it to an f string for you you know what i don't like about them yeah i agree that's awesome what i don't like about them is i type i type i type i type and then like oh i want an f string i go back i go back i go back i go back i put up i go forward i go forward i type that's why you do alt enter and let pycharm do the work for you you just you go over and you just type lo yeah that's right it'll prompt you oops is that you the right one no you gotta close it i think i thought i just had to type location i said not do it come on it normally does it what's going on anyway i i do love how it normally does that but why is it not anyway uh city and let's let's wrap this around state this is close it's not quite what i want this would be country so what i actually want is i want to take this little bit right there i want to do it from this direction actually and we'll say if location dot state so if you pass a state in url plus equals ampersand state like that there we go we just add it on otherwise that's going to mess up the api and then what we need to do is we need to call it now i could just do requests like everybody says oh install request request.get you're good uh except for you just gave up like insane levels of scalability right because what are we doing we're waiting on the internet not on our server not even on our database we're waiting on the internet the internet's quite scalable right so if we put the word async here we can do nearly unbounded amount of waiting at the same time right i mean some days you wake up and google login doesn't work not even youtube or gmail no so we can come down here and i can go i want to also use this thing called httpx so you saw this in the list you can install it and we wait and this thing is super cool and i can also add this one i really do need to add to the imports because it's not pre-included so what i can do down here is i can say async with that's a bizarre construct struck to me but it is nice httpx.async client as client and then i write request cloud so i say response equals httpx dot get url response dot raise for status return response dot the text like that uh no i don't want to turn sorry i want to say um not text i want json there you go just see data equals that and then i just need to well let's just print out what data is real quick okay so we can see have we done actually uh sorry i did miss a little bit there i was still in my my uh request mode okay so click the button again i didn't love it what do i get raise for stat what is my status what has happened here how about we print response dot status um the status for status code i don't remember i think it's status code print response dot text whoops they're saying there's a typo in the f string url is not correctly formatted move the city after the equal oh thank you folks what the error i'm getting then let's let's see the error though but yeah thank you very much and then you got yeah the trailing equipment yeah i got it just uh drop into the debugger man i should have dropped in the debugger the error what we were getting was either malformed url or probably you know validation that city was required and missing so anyway let's try again thank you everyone hey look object co-routine there we go perfect so it has no raise for status because this the this is an async method so we need to await it there we go now what are we doing dad something went wrong but we got the answer i didn't know what was wrong i just somehow messed it up what is the error here oh yeah i just didn't set my didn't my umbrella is not filled out perfect so did you notice we've got our data we couldn't return whatever but look we've got our description it's misty i can look outside and tell you it's pretty much a 90 of what it is for like six months here and what we want to look at is this category so we're going with the weather and there's a category so so we make it this far i want to say whether equals actually this needs to be above data.get weather and then category equals weather.get category and let's put a make it sort of flow through there in case it's empty for some reason and then we'll say none or not available but as a string okay how about unknown or unavailable all right and then are you ready for the umbrella so actually we could do whoops this just to make it really clear when we're out of async mode out of that http mode and i want to create an umbrella equals umbrella status and what can we put in here bring umbrella equals bring and temp equals let's go back to our so we got our weather which has a this and we have our wind and we also want the forecast temp so forecast equals data.get forecast and then the forecast is going to have a temp and then we'll be all good and we don't know what that is it's an empty dictionary and then temp is forecast i get temp and it's going to be zero i don't know and this will be the temp now this bring thing what i need to check is bring equals category dot lower dot strip equal equal rain how's that look it looks like a good implementation there but will it run but will it run well if it does we're shipping it okay dude look at that all right uh let's go maybe seattle let's go i need to find a place that's raining someone help me out here where is it raining right now um show me the weather map or forecast i had not considered that i might not know where it's raining i figured surely where i am would be effective let's see vancouver vancouver all right uh vancouver bc right okay so pepe all right vancouver and country equals ca all right hold on let's see what we're getting from there let's go into the debugger this is a whole another challenge paul i hadn't considered is knowing words here you are thinking about you know async and event loops the problem is it counts as missed let's just say it's also misty here like i always have the same weather as vancouver let's say let's change this to in a set rain or mist okay there we go yes we got to bring the umbrella and you know where it's not raining san diego it's not raining in san diego i live there always it's a good safe bet yeah look at that we did it we built the api that says should it uh is should you bring your umbrella yes or no we could make this a little more clear because like there was that confusion there um we could say the weather is a string yeah and then we come over here and say weather equals [Music] category just put it in category that way it says mist or snow or whatever yeah it's clear in san diego but if we go back in vancouver it's missed we did it 10 minutes and now we have our own mashup a la 1999. what do you think paul and i like that um from the perspective of complaining about validation problems and things like that it was using kind of semantics that are now built into python rather than invented somewhere else yeah absolutely and one thing i think i just picked up on is if i say new data equals umbrella dot um dictionary a straight dictionary i return that i think and i take away the weather yeah so look it even tells me that my contract with the return value couldn't be created so it actually created it too and converted it to an umbrella status because of what i had up here even though i just returned a dictionary and another thing to notice that's pretty killer like we don't really need to do that return umbrella another thing to notice if i go straight to the data what is that right there that is not a string that is a float and i'm pretty sure even if i said that this is a string of the temperature what we're gonna get is yeah still it's still pedantic is saying it was a string but it has to be a float so it's a float so all that type conversion and stuff now obviously we don't need to do that because it came back from the other api as if i float and whatnot but cool right all right well i i didn't expect the hardest part of this thing to be figuring out where it's raining in the world but here we have it so i think this is pretty slick man i mean i wouldn't write it like this i would do one more thing i would do um i'd come over here and i'd factor this out create a like a services and i'd call this uh i don't know i'm out of names live weather service or whatever and i would put this this bit into it you know something like maybe maybe even this i'm not sure but certainly would put something like this over here async def get live report look location as that and then i'd say up here from services import data equals await this location there we go so now it's you know less like we're not doing the api calls right here like we're just sort of that way that would be easier to test or easier to mock or whatever let's just make sure i didn't break it i did what did i do oh i think i forgot to return anything that would help return data none does not have a get there we go cool right sorry i wouldn't like jam it all into that one view method here right that seems wrong and you could even do one more one more pie chart ctrl t not every name ctrl t in line there we go all right i think we're good questions all right yeah we'll switch over to our very long list of questions note to all this webinar is going to go a little longer than an hour uh within hour well the q a may run over huh yeah you're perfectly on time how about that all right um lots of questions at various levels of depth and things like that um small detail someone brought up in the chat you can actually use whiskey mounting to add flask to a fast api yes you could well you could use whiskey mounting to add any whiskey thing you could add django you could add flask you could add other fast apis that's right that's the thing that i was talking about but i have no idea how to do it i'm sure yeah and it kind of brings up a good point that was also mentioned several times in the chat was uh we talked about this being built on pedantic it's also a lot of stuff that you just showed is actually starlight could you talk about starlet certainly deserves a huge credit this is a programming interface on top of starlet's functionality really it's like pedantic plus starlet so for sure tom christie and crew over and code need credit for that as well okay um this is one uniquely designed to appeal to you and me and our inner pyramid self yeah got it there's a complaint about having to pass passing like a global database down always passing passing passing and as opposed to presumably having some magical thread local that just appears upon demand and you can never debug it uh do you want to talk a little bit about that pattern of always passing things in uh so like the the dependency injection thing so yeah yeah so what you can do i haven't used it extensively i'm not sure where you register but you could say this function takes like a dictionary a database implementation like a a service or a it takes something that like creates a sql alchemy session or something like that and you know it should get passed in through that dependency injection which is it's pretty neat it definitely makes testing easier because you create a mock one of those and just pass it indeed indeed and then it's a common pattern in pyramid to have pretty skinny views and move things out and put them on the request object or something like that okay uh two things that i really desperately want to talk about pycharm has some unique facilities to help in fast api yeah i didn't talk about the uh the the the plug-ins right getting the plug-ins we'll go over a couple of things that are built in um instead of going over the browser all the time and hitting refresh there's something called http files where you can edit a file in this kind of curl like language and have the play button and it issues a rest request and it's got all kinds of facilities to do the things that you would want to do for testing front ends uh so that's a pretty cool thing um if you have a database back in their questions for you michael does your course use a database no it uses an api like this okay cool all right uh i considered having one but i i didn't because it just it's like another level of stuff you've got to set up fast api yeah yeah so we'll get to the thing about databases but if you do have a database pycharm has the database tool that lets you browse everything and complete language stuff like that but even has mongodb integration these days which thank you he did it was the michael kennedy feature thank you that's the way we referred to it internally perfect um the couple of things though that people might not know about is uh community plug-ins that we helped the people write in one case we actually put an extra like api kind of plug point in for them the first one is from kudaiano uh who did a pydantic plugin so um do you want to talk about that do we need to go back to your screen to show a url i use it i don't know what i'm getting from pedantics plug-in versus that's right so you you help me out and tell me yeah yeah what i get by doing that i know i want it i just don't know why the idea here and this is a riff that i wanna if we have time later get on to about modern python and static analysis is this information is used to validate incoming data right but it can also be used to give you autocomplete and red squigglies now an issue is like in pycharm we support data classes and we'll do autocomplete and give you red squigglies when you call something incorrectly but the base model in pythanic isn't one isn't a data class so it pycharm needs to be taught that this is one of those things that has special semantics if you use the data class support in pydantic out of the box pycharm is only looking at python's built-in data class and since python doesn't really have protocols or interfaces we can't really say that is also pretending to be a data class so he and his plugin taught pycharm to do all of these cool static analysis auto complete refactoring code generation things for you go search for pi pycharm pedantic plugin install it he's done a great job on that plug-in release after release after release engaging people closing issues staying current with the latest pycharm releases he also has a plug-in for poetry it recently went 1.0 and he's also been plugging you know adding features and closing bugs and we had to do some work to uh help him on that so those kinds of plug-ins are really interesting and there's another plug-in that people can get i'm almost positive they don't know about if you search for uh what would it be uh intellij open api specifications there's an open api swagger plug-in that brings in this new universe of endpoints and it's weird man it's so cool uh we will know the things you're defining and then autocomplete them in other languages for example in javascript you'll get auto completion on url strings to fetch based on the models that you've defined we have some work to do in 2021 stay tuned on that but this kind of gets into a question that came up uh depends actually two questions depends and return type response yeah response type someone noted and i agree with them they shouldn't be using the pins they should be using the new python annotated thing which does have a back port for earlier python versions do you ever have you ever heard of this thing no my type hint stuff is all focused on you know three five three six and above so i haven't really done it it depends makes sense there dependency injection is i have a dependency of the application i don't want a password i don't want to make global like you said i want to pass around but i want the trouble of instantiating it each time i want it just when you need one of these here's where it comes from sure arguments to a function don't seem like that to me so that's a little weird um it's interesting though because uh it's kind of done in other places where like for django models you have this magical config class that you sprinkle in to explain to the system its dependencies yeah data dependencies annotated is pretty cool sorry i know a lot about this tell us about it like this weekend spent 10 hours in my code on writing a dependency injector that uses annotated it's a way to say here's the type information but also here's some extra metadata that custom tools might use yeah which is exactly what fast api is doing and so it's got a generic call depends when really it could be using this annotated thing any idea why you have to do return type instead of just getting the function annotations response value response type yeah so that's an interesting thing as well right like what i expected is i can use the inbound arguments the function parameters and it'll detect those it doesn't detect them for pi titanic models but if they were bare arguments like city equals of city code equals float than it would i thought arrow umbrella status would have some influence like the the annotate the type type annotation response type would have some but it ha it's ignore it has no meaning you have to say response model i'll have to go dig into that and say they probably have a good reason there probably is a good reason i don't know what it is yeah it maybe it's because they want to support versions before python 360. but it depends three six is a minimum requirement for fast day so all right i don't know next one's easy for you why chameleon why not just ginger too michael oh 30 seconds or less 30 seconds or less what i my screen's not here it's fine i don't need it um so i'll do this with words what i really really really dislike about jinja about django about other similar types of frameworks syntaxes is you write broken html if i were to go over to some tool that doesn't know what jinja is and i say this is an html file well this is entirely broken i've i've no idea what to do i give it to a designer in like a a you know web design workflow they're like i have no idea what to do with this junk like this won't load into my tooling chameleon is 100 valid html with some extra stuff that gets ignored right i mean you might say the attribute towel doesn't make sense on a div but beyond it's you know the browser's job or behavior is when i see attribute i don't know is ignore it right so it feels like view it feels like i can write valid html and it just happens to be that it gets expanded out or has more meaning some people i might this my guess i have no basis for this i believe their their feeling is i don't really like this because in those other ones i can like write full-on python code in my video and do whatever i want to me that's a bug not a feature you should tell a little historical story about that yeah man you shouldn't be writing that code in your view it should go somewhere else back to your application right yep chameleon comes from zotpage templates which is that template attribute language syntax uh and in 1999 luciano ramallah and i independently at the same time invented that i was on vacation i wanted something that worked with dreamweaver of all things he wanted something that was partiable with a regular xml parser and so it's interesting that your interpretation of why you give a bleep about it was the original reason that we came up with that you could walk over to some other tool it's beautiful i can look at it i can write html and then i can make it dynamic all the other ones you're like oh did you forget to end four like why am i writing in four yeah right if you want me to write python make me indent it or something you know what i mean yeah there was actually an uh an implementation in javascript um of chameleon okay or as page someplace um someone asked a question about nested urls nested routes or whatever in fast api can you do it nested urls uh like the router has some part of a url and then maybe like a sub url it's almost like traversal you you grab a person and then you grab what department they're in and then you grab what city that oh i see what you're asking so slash people slash michael slash department slash marketing i had to do that to you yeah let me um let me check well let me just check something real quick here my little i know you can't see it doesn't matter it's just i'm pretty sure this works but let me check it before i say that's what i love about programming you don't have to debate you run it it says yes or no so what you can do on this is not exactly what you're asking i i believe so i i'm going to say probably no in that regard but what you can do is on those routers you can put a url prefix so for example on mine i said directly in the router.get url it was slash api umbrella what i could have done is i could have gone to the router and said everything in this file is a slash api and then just put slash umbrella slash that so you you can sort of as you define the files you can create like a hierarchy as sort of as but i know it's like i'm not in um navigate the data sense that i know of right like not like well i got the customer then the customer has orders so i do slash customer slash seven slash orders slash like i don't know anything about i have never seen anything like that christian mueller in chat saying that it's path params you can do slash pass curly brackets whatever slash another path you can do that i don't know how that traverses data objects sure right okay next question um in may i just don't like i just have no idea sure uh so we've run i think there might have been some questions the last couple of minutes that i didn't get caught up on um the kind of point that i wanted to close a little bit with and riff on if that's okay is the whole static analysis part yeah i mean we've been talking about type yeah semi static semi yeah yeah and the reason i wanted to bring it up is you know fast api is hotter than the surface of the sun yay fast api and one of the two big killer features is pedantic and the reason to give a crap about pydanic is type heading yes and so this is a case where you eat your vegetables but you actually get a direct immediate benefit yeah absolutely yeah and there's go ahead sorry no um someone was walking i just told them okay and there there's um more of that that's beginning to happen in the world of python and python feels a little bit different than a few years ago and there's still this tension in the world of python with these people saying leave all that crap out i wanted to write read my code if i wanted to write java i'd i would just go get eclipse and i'd be happy or intellij says every rage tweet ever yeah there are five million entries in reddit that say that yeah um but this is a case of you get the benefit from you get something that has broader tooling support you could point my pie edit it would find places that you messed up most importantly smart editors give you red squigglies yes and from a developer even if you don't care about rec even if you don't care about that did you see how quickly i wrote this without ever going to the documentation sure it doesn't mean i know everything i don't know if it's a lowercase p lowercase i or capital api it's it's it's code generation plus code value that's right yeah that's right and um your tools like us don't have to be taught these little silos of hey you know in a django thing over there's this thing called the view and they're usually connected by this magical string and that's how we will find out and do static analysis and do red squigglies instead there's this common system that all kinds of tools can run on and give you the equivalent of red squigglies and i just i wanted to bring that up because of pydantic but this benefit for um stop doing the get off my lawn and embrace the death star of type inning because good things are coming man and it's not just you get validation on your incoming http data it's a developer experience which is more positive um open api too yeah and yeah it is and lucas linga spoke about their work at instagram converting everything to type annotations and finding tons of bugs and getting rid of them indeed yeah and i saw this freaky presentation at pycon back when there was a book about finding security holes via static analysis and type hinting oh wow okay and it was i'm not smart enough to know anything other than it was it was pretty fast yeah that's awesome so just trying to make a pitch for this um lots of places that this meme will begin to appear and your tooling will help you write better code faster based on doing a little bit of extra work yeah there's there's some part let me see where where is this thing there i believe it's the validation decorator there's a part of pydantic that was recently in beta and what it does is it actually turns yeah yeah it's called a validation decorator and what it does is it puts runtime verification into those type-ins uh-huh so you could actually throw this decorator onto it and it'll say no no you said it took an int and you passed a string i'm not sure if i would run in production with this but it might be like okay i've got an api and at the boundaries i might write i might wrap it in some decorators see if we can track down those bugs and get everything figured out and then take them back away yeah brilliant yeah okay you want to make about your course or about fast api sure uh i can say something about the course whoops if i don't go past the end of my presentation people can check out the course i wrote a four four and a half hour course that i feel is the 80 percent case of what most people need to get started and be productive with fast api it's over at talk python.fm slash fast api and it goes all the way from building some kind of interesting app that's similar to what we did here but with a lot more digging into the details about things like pedantic and so on and then we actually deploy that out on digitalocean on ubuntu and so sort of end to end you know start from idea get it running in the cloud all right and is it part of any promotions that you're doing not currently it was for black friday but now it's okay now it's not all right cool all right let's go ahead and switch back over to my screen and we will go ahead and get this wrapped up thanks michael as always i could uh i could just listen to your silky smooth voice all day long which is okay because there's talk python to me podcast yeah also really quickly uh there's also an interview with sebastian ramirez about fast api around 284 i'm not sure exactly when it was but it's episode 284-ish around what month of that would be about two and a half months ago oh perfect all right yeah so it's pretty pretty fresh all right well thanks for taking the time to talk with us michael about this giving us a real quick working introduction answering the blizzard of questions everybody go take a look at his training course uh exceptionally well done all of his courses are exceptionally well done if any of you have any questions later don't hesitate to contact us by email by social media i'd like to hear from any of you about your thoughts about fast api about what pycharm's doing with these kinds of things we had a lot planned in 2021 so now is a great time to let us know what you think if you'd like to get more information on pycharm go to our website jetbrains.com pycharm if you haven't already check out our blog where you can find up-to-date information about news our recent release for example other kinds of events such as this we already know what we're doing for the january webinar for the february webinar etc so you'll be able to find out those things in addition to educational resources such as this webinar we'd love your feedback on this webinar this cool new format where i get to hang out with michael kennedy and see his face while he's talking uh feel free to contact us on twitter in the after webinar survey which we will email you in a bit that's all for us today thanks so much for joining thanks so much for staying to the end hope you have a nice day yep thank you paul thank you everyone for coming see you later you
Info
Channel: PyCharm by JetBrains
Views: 41,349
Rating: undefined out of 5
Keywords: FastAPI, Python, API, pycharm, webinar, Michael Kennedy, Python 2
Id: sBVb4IB3O_U
Channel Id: undefined
Length: 79min 16sec (4756 seconds)
Published: Tue Dec 15 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.