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.
Enter aiohttp
The
pip install aiohttp
The API is similar to requests. Here's a GET request:
import asyncio
import aiohttp
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.example.com') as response:
print(response.status)
print(await response.text())
asyncio.run(main())
Async contexts like
Client Session
Reusing a
Handling Responses
The response object has async methods like
Exceptions
Any exceptions in async code bubble up to the top try/except block. So wrap your requests in
Going Further
That covers the basics of async HTTP with
The