Python's requests library makes it easy to make synchronous HTTP requests in your code. But in async environments, like asyncio, you'll want to use an async HTTP client instead. Here's how to make async HTTP requests in Python.
Why Async HTTP?
Synchronous requests block the execution of code until a response is received. In async code this wastes CPU cycles waiting idly. Async requests allow other code to run while a response is pending.
For I/O bound tasks like HTTP requests, this allows full utilization of your CPU cores. This means better scalability and performance.
pip install aiohttp
The API is similar to requests. Here's a GET request:
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.example.com') as response:
Async contexts like
The response object has async methods like
Any exceptions in async code bubble up to the top try/except block. So wrap your requests in
That covers the basics of async HTTP with