thank you uh first I want to say hi to my mom hola mama Andrea my girlfriend and now we're going to talk about uh the fast API internals I'm going to be talking about some stuff there youorn stet identic I was here in the previous talk it's really not the same it's it's more deep stuff so yeah uh I'm Marcelo trzinski uh I maintain Yorn Starlet I work at pantic so I also maintain a bit pantic and yeah that's that's pretty much and what else yeah I maintain those and what's fast API uh oh yeah
is there anyone who don't use fast API here like never used never used okay uh cool uh yeah the thing is it's going to be more intermediary kind of uh talk so I'm going to be talking about deep stuff so anyway fast API is a web framework uh that really uses the type hint at run time uh it uses it has two dependencies uh stallet and pantic and it has been very popular lately because of how easy it is to C uh the experience is very nice has automatic documentation data validation and all the things
that are under R me and how do I run fast API I can run fast API with many stuff which was also said in the on the previous talk uh the server can be youth corn which I maintain can also be hyper corn which was uh this just a bit of propaganda for the other web servers as well so hyper corn was created by Phil Jones he is a maintainer of flask as well and he has a web framework called quart which is the async ASG compliant uh that tries to maintain the same compatibility as
flask and there's granum that guy there uh it's a web server that supports asgi uh he's Italian so Italian and it's written the HTTP parsing is in Rust right yeah and also uses UV Loop by default but uh still use youorn please so how did interactions happen so I'm going to be talking about specific part of this F but pretty much the client initiates the connection the server accepts and then sends data to the server and then the server on its turn sends data to the app on this uh diagram you can imagine the client
as one thing and the server and the app as another entity uh but I put it three steps here because we're going to focus actually on the server and the app and how they interact and the way they interact uh uh it's defined by the asgi specification which uh yeah a synchronous server Gateway interface well it's pretty much a way you define how you're going to interact from the server and the application how they are going to communicate between each other and this is pretty much the interface of an application in uh asgi so you
need a scope which going to tell you information about the connection uh you're going to have the receive and send which are two calies one uh is used to send data to the server and the other is to receive data from the server um yeah that's pretty much and what else this is the most simple as application on the on the previous talk there was an example copied from the uorn documentation but uh the read me lacks one thing that's the content length we need to fix that but this would be the full simplest AS
application you have your body you have uh some headers and you are not receiving anything from the client so I'm going to only send in data this is an app so I'm sending the the data from the app to the server and there are two uh asking messages being sent here the HTP response start and H3 response body uh there is one specific thing that happens different on uh the web servers I don't know how it works in granum but in iorn you have the the response uh start but this is kind kind of important
but the response start is only sent uh in the hyper it's only sent after the response body is computed uh this is a different Behavior than uorn which I guess most of people use it based on the downloads so uorn actually sends the response uh status like the the response start first and then you have the body being sent after so sometimes you might see an exception on the server uh if you are streaming some data for example streaming response from Fast API but actually you see a 200 and then you are how this happen
why is not a 500 because we send the response uh headers first and the status code so the response line is being sent first and then you have uh the body being sent after iorn do Des sends those two together this is what happens this is what you see is the all the data that you send from the server to the application during after the connection is established and uh well the server receives the request line so we par we get all the information about uh the connection so the client the server address the method
root path path and all that information that you see there so this is what you saw on the asgi uh what you saw on those previous slides here this is what goes to the scope part so this information um should should not change during uh the the response uh request response cycle unless you use state which I'm not going to talk about but lifespan state is also a new thing which is support by uh uorn and granum is not supported by hyper Gorn so when there is a connection you receive you already have the scope
but then if the if this client sends a request then what the server does is that it receives the request it passes the the request you youorn us HTTP tools if you install HTP tools otherwise it uses a package called h11 which fi Jones is one of the maintainers the guy from hyper and it sends to this to the application the HTTP request message as you can see we are only sending the body which is I have this it sends the data the those bytes only um then this the app gets the the HP request
and then sends back the HP response start and then the body so I'm saying all this because this is the basics of fast API now we're going to go to fast API itself we're going to talk about Starlet you've sorry Starlet and pantic a bit more but this is just the basics of what's underneath really underneath um well there is more underneath far but this is the python level goes to there uh so the middleware stack I'm going to talk about the middleware dependency and all the validation when it happens on the flow of receiving
the data and where it goes back to the to the server sorry to the client uh so on here you see the server the middleware and the application the middleware just stands in front of the between the server and the application and the idea is that uh on Fast API you can add the middlewares in this way so you just add add middleware and custom middleware or using the the parameter middleware uh both can be used so in this I'm adding first the custom mdware and then the another custom middleware right and this would be
the whole flow of middlewares that you have on Fast API if you are not sleeping you have the server arror here that's different from like it was not it didn't appear on the last on the previous slide and you have the exception middleware as well so those two are already in the framework itself we have uh building uh middleware the server error where is it I lost it here the server error is uh it happens when uh you have an exceptional application and it just make sure that you are sending the 500 to the client
back so you need some kind of wrapper it could have been in the in the server uh on on uorn but it doesn't happen like that so based on this pack we have that handling on the application so we have the server error midw just just make make sure that we have a 500 on the client side and we have uh the exception ah exception middleware that's the one that handles the HTTP exception you know when you put at app. HTP exception thank you so that's where you handle custom uh exception on your code or
different status code so you can you use this exception windoware that's on top of every on the whole app to see which is going to be how is going to look the the response for those uh status code or exception and then it goes so it goes the server middleware wraps everything on your application then there is uh the exception middleware so if you have an exception on your application it goes here you see the application with the exception on this custom middleware another custom middleware then on custom then it goes up if it is
one of the exceptions that you saw like that you defined on the HTTP exception uh decorator then it's going to be handled here and the exception is not going to go up to the server error okay so for example if you handle I don't know 400 and 21 I have no idea which one is that uh then you're going to send whatever you defined on this uh on The Decorator if in case it's not defined here then it pops up and you have a 500 handles it and sends a 500 and then the it sends
back to the server the server is responsible to send to the client uh that information ER yeah so that was about the the midare that's what happens now we're going to add the concept of rooting which uh different apps use different uh rooting algorithm but anyway so and of on Starlet which is responsible for both mware and uh the routing there's no there's no fast API in this part there is it's just pure Starlet what happens is that you have your middleware running you have your application uh okay so let's go back this the client
receives the client sends the data the service receives the data it sends to the middleware and then it pass through the application and on the application we Define to which end point which end point are we going to run uh so it choose the endpoint and then it runs the end point one possible problem about this and some people have request is that you don't have the information about the rooting on the middleware because the rooting happens after the middleware runs so for example if you want some information about uh which endpoint run then you
don't have that available uh on the middleware before the app runs um yeah that's that's what I have for this one so on this one I have two end points here I'm going to ask a question so pay attention the ones sleeping uh so uh I have a s a simple fast API application here with two end points I have the one that has on line six I have only a name as a path Pam and on line 11 I have just the endpoint potato if I go and I like I go on my terminal
and try to make a request to 8,000 suppose I'm running on that board 8,000 SL potato who thinks uh the endpoint on line six is going to run raise your hand okay who thinks is the one at live line 11 okay who doesn't think anything aha good job so um it actually runs the first one what happens in fast API solid is it checks the each path one by one so it actually finds the first one being a match so it goes to that one it doesn't proceed to check the next so what you should
do if you want potato to work you need to put potato on line sex six and then change to line 11 yes covering the same like the name can hide the when you constru the name can hide the potato yeah what do you mean no no I didn't get it already Satisfied by ah you were asking if you couldn't handle that on on the web server on the on the application can yes but I don't so thank you for the question now we have the pendency injection so here we have three dependencies one it's called
call a one's called call B and one is called dependency okay this is just on line 33 to 36 I'm just having this uh counter here called to just to increase the number to see what happens I should have deleted from for this slide because doesn't make sense if you see you don't see it running but anyway so uh there is a sequence of how this those are running and the sequence so you see call a is calling uh dependency and call B is also calling dependency right um so what happens in this is fast
API now it's not more stallet stallet doesn't have dependency injection uh so you have the app the endpoint function uh the signature well the handling uh it's going to call the call a and then it's going to call the dependency this is the order the red thing here gets to the dependency it gets the result and it comes back to call a with the result and it goes back to the the app so it's already constructed the first part so this part here the a it's already built and now what fast API does it's go
to the next dependency on the signature and it tries to see in the cache so oh I forgot to say those those green lines here is that starting in a cache this cache is per request so per request response cycle you have this so um I call B and then B checks in the cash if the the results of the dependencies of the dependency is there if it is it comes back comes back to the application again and that's what happens so this is very important now this is a concept that's not written anywhere I
think so lucky you uh I have async and sync dependencies Ayn and left syn which which one you which one think that I should use the one uh on the right raise your hands ah uh my hand here on this side uh who thinks we I should we should use this one in this in this case it's just returning the strings not doing anything okay who thinks should be on this side who doesn't think anything H okay so this is a good tip then uh you should use the async de here why who knows why
no one yeah is running is going to be faster anyway because Loop that yeah it's that good job so uh yeah it's pretty much that so you just should use the I think in this case because we not processing anything there is nothing really blocking the well you know it's going to run this and it's going to send back right away to the to the Point otherwise with this one you're going to be running in a thread pool uh it's just the overhead that you don't need and also an important information fast API if you
don't change the default it will only run 40 threads at the time so right now if I uh use this there are 40 requests being received now and I am running only this I cannot receive more well it's going to block on the next one okay uh you can change that default that's not as fast as fault neither startlet it's on any iio that the default is set as 40 so you can change that number and this might be one possible reason for why some code might be blocking because you don't have enough uh threat
on the other hand if you change the default to a number that's uh well pretty high you might have other problems but uh yeah just be aware of that um input how I'm one time okay uh input output validation I think I think I need to run so uh on this application I have the input and output uh this is another feature of fast API in validating the input output that we sent uh from the to the endpoint and fromont endpoint so online this one I have a sync the red item uh I have the
input being received and I send back I insert something in the database like this input and then comes back and then I validate the result with uh the output which has the fields name age and ID how it works it's pretty much like that validates input runs the endpoint function and sends back the output validation the difference is that if there is a validation error from the input you send back a 422 and if there is a valid a validation error from the output you send a 500 this might be not news uh so anyway
another feature is the web sockets this is uh mainly Starlet the only thing that uh yeah the only thing that fast API does here more than stallet is it reads the typeint websocket and it pass the websocket object to fast API I'm just accepting uh the doing the handshake the websocket handshake and then uh I'm receiving some messages online 9 and send back the same message to the client and then I close the connection online 11 handshake and then data being sent uh yeah so I just added this slide because I thought it would be
useful uh when should I use async and when should I use sync you it can be another person as well it can be me doing anything that is uhhuh I know a tricky question like about the S part maybe when it doesn't take a lot of time and you just and The Return part immedately it's don't worry about it so if it's uh thread iio blocking then you should use sync if you can you are running uh CPU bound and you are block and it's you can escape the G some packages like numai or pandas
they have stuff that you can escape then you should use sync uh if it's CPU bound but it doesn't escape the Gil you shouldn't be running that on the web server anyway so try to to throw that to another uh worker or something this is a repository that I created lately which I gave give some small tips that help a lot according to me so fast API tips on cloudex uhuh pictures you ready thank you so uh trog fire I work at pantic we are building this new product it's an observability too uh we also
have a booth there I there's a I am doing a demo on the screen um and my boss the P identic Creator is there so just go to talk to him and that's it thank you [Applause] all right thanks for the talk uh we have a couple of questions keep them coming in room lasagna on slido wait now they're gone give me a second it's not loading come on Ed ah yeah out there okay first question can you use graphql with fast API it was you no no no someone else yeah uh yes it has
an integration on strawberry Strawberry yes which one graphine strawberry no you can use strawberry use strawberry guys um next question what are the trade-offs of having a server error middleware instead of managing errors into the server itself ER I don't know I think no no I think I think hold on Cal down I'm processing here uh I don't I don't think uh I think the Asis spe tried to match what you aski tried to do so that part is just handled by the application itself I just think when they create this P well that's what
I think they just didn't put that handling on the server side was they just defined to be on the application side all right next up is it possible to use fast API on top of Django basically making an async version of Dango T I think we have that question with flask the talk before so some but but but there was more than the answer that was uh there uh so you might try to do that if you are migrating from one framework to the other and you might want to do that to migrate slowly to
fast API uh for Jung I'm not sure if it will be worth because of the uh orm that they have and stuff but for flask you can you can Str migrating step by step like you put the the uran with uorn and then you mount the flask into uh the fast API application but then so you would be running two at the same time well we'll be running uorn and then creating end points only on Fast API like transitioning slowly that's one possibility all right can you use HTTP 3 you with fast API uh yeah
yeah okay quick answer when would I use Starlet directly instead of fast API good question for you I guess uh yeah I mean um it was you it was you I knew it uh so sometimes people think that what fast API provides is uh not needed for them or they just prefer to handle some of the parts there what else can you include in this I'm speaking yeah that's true so yeah um you might want to so you might want to generate What fast API does like the automatic documentation by yourself you can add a
decorator to for example on the on the on the startet endpoint and then customize receive some ptic models Anyway by yourself so all right I don't think that answers two more questions one is is there any way to connect engine X directly to an HGI server without the need of an ucii in middleware in the yeah I heard this question on the last talk but didn't you see like they have that on I'm asking no yeah but I mean if you if if you I think if you Google like any and how J they have
on their page they have the ask itself you can do it I never tried but like if I go here like uh like there is what is the page well they might not be that popular uh I thought I think I saw it some years ago didn't I well we can talk later but I think there's a they have a page on their dogs about it or something like that what is it I think the last question is from us ra right come on just ask it in person if you're already talking uh okay um
I usually have the situation where I should return to the client HTML not just just on data so if I return HTML is just computationally heavier than Jon when the request must be buil must be built by the response class I mean no no and also in that case you can use Starlet because you don't have anything fast AP Rel but no all right one more question you you're not uh it's just I no maybe on the templating no I don't think so no I don't think uh um I would say no you might prove
me wrong no no I I think no I think the answer is no all right last question in slido uh if your fast API is using a rate limited back end how can your fast API app know when to reject requests for example with a 429 status so where you have a I think it's meant you have a fast API application and then it accesses another service that is rate limited did I get that right and then how do you know when to reject requests so you have your fast you have an endpoint and then
you call some other service and then it returns maybe someone wants the other service does not return error but that your can only call you have to like know how many requests in total are accessing so that you can only have like 20 open connections so you have to count like you have an end yeah I got it like potato yeah get it I'm 20 potatoes but I can only serve 10 potatoes so like if somebody else has asked for the 11th potato and I have not served the 10 ones my fast API should not
ask for another potato uhhuh how how do I manage that state so you don't want it to block or something to ask because I know this thing is not going to get I know I have 10 open requests for potatoes and until I get those 10 potatoes point and if I ask it it will me a late later will ah and then you need to got it again later like in the production there's que like a que with jobs and I don't want to put too many jobs in the que I don't know no I
mean uh so I have two options here either I send a request and I do something after which you don't want look like but maybe basically I was thinking of like I have a global state where I how many I only at the reest well you can you can put you can put the oops I'm so sorry about that so you can put the the client on the lifespan state so you have the client there and then you can check the number of connections that are already on the client okay so you can do that
you have the available the number of connections on the I mean if you are talking about htpx for example you can have that information and then you yeah we can talk later as well great any more questions in the room I'm happy to yeah I I think sometimes someone recommended me to run on production servers a combination of I think gonor plus uh uicorn to spawn multiple servers and then in every instance you have a work with um a different like ashd server serving the whole thing uh is that still the recommended way to scale
fast API apps what should I do to scale the app uh it was uh never my recommendation H so what's written in the documentation is a way uh you use junicorn to manage the uorn pro processes so when when uorn process dies it uh does the survival thing and it gets one back again right uh but then nowadays people like kubernetes and stuff and it's simple to treat the unit as only having one uorn uh worker and then put the resources according to this so you have one you you put the resources there according to
this then you scale the yes yeah but also uh this is new information I'm waiting for him to leave so I say it if you have the junicorn like right now I'm dicating the Unicorn worker so with junicorn you'll you have the there's another package that's been created called uicorn worker so we can do that but uicorn itself is going to have the process manager on the next release so if you still use uh junicorn with uicorn you can uh remove junicorn on the next release all right any more questions we have some time left
in the slot cuz this was a shorter talk um and if you have any questions just raise your hand all right doesn't seem to be that way then thanks Marcelo again