Modern APIs with FastAPI and Python Transcripts
Chapter: Modern language foundations
Lecture: Concept: An async method
0:00 We saw how powerful asynchronous methods can be. Let's just take a moment and review some of the core ideas around building async
0:07 methods. Normally, we define a method like "get HTML" as "def get_HTML" but if you want it to be asynchronous, you say "async def get_HTML" right.
0:16 We're gonna be doing that within FastAPI all over the place. And then we have this somewhat unusual construct called an "async with block"
0:25 and that's probably the most unusual thing in async amd await. And what we're going to do there is the actual with Block is opening a network
0:31 connection, opening a socket, and so we want to do that asynchronously. It actually takes a little bit of time
0:36 if you just create these separately without the async stuff, it's quite a bit slower. So this lets us open all the sockets at the
0:43 same time, and then we're gonna issue some of these requests. We're gonna say "client.get". Now
0:48 normally, that's just a blocking call and you get a value back. But when you call an asynchronous method,
0:53 which client.get is, what you get back is not the return value. It didn't even actually run. What you get back is something called a co-routine
1:01 that if you await it, it will run and give you the value. So here, we're going to say, "await client.get", get the response,
1:07 and then we just work with it normal. The big takeaway here is that where you see "async with", where you see the word "await", all of those points,
1:15 if you're waiting on some external system, your program, in this case, the web scraper, more generally, probably the API server, will be able to
1:24 actually handle other requests and do other work until this client gets back to us with its answer, then we pick it up and run with it.
1:32 Often, people think of this async await as scaling the computation or like adding threads. Threads are not even really involved.
1:39 What it lets you do is it says it lets you mark different places in your function that says "I'm waiting on something other than our program.
1:47 I'm waiting on something external, you can go to other work until that gets back to us" right? So here we're waiting on the talkpython.fm server,
1:54 could be a database, it could be something else. So it's this async with and await where we're marking,
1:59 like, "here you can go to other work until I get this response and then please start me up and we'll keep running".
2:04 And that's how async and await works, and because most Web applications are waiting on something else, they're talking to databases, waiting on them,
2:12 they're talking to other API's, micro services, and so on, waiting on them, you can do a whole lot more work if you can find a way for your Web server
2:19 to allow it to work on other stuff while it's waiting, and that's exactly what async and await does for us.