How do I create a Python API client which executes *some* methods asynchronously in the background?

I have this (example) REST API client:

import requests


class FakeHttpClient:
    base_url = "https://api.example.com"

    def __init__(self) -> None:
        self.session = requests.Session()

    def get_user_info(self, user_id: str) -> dict:
        return self.session.get(f"{self.base_url}/users/{user_id}").json()

    def get_users_info(self, user_ids: list[str]) -> list[dict]:
        return [self.get_user_info(user_id) for user_id in user_ids]

if __name__ == '__main__':
    users = FakeHttpClient().get_users_info(["1", "2", "3"])

I am trying to rewrite this using aiohttp so that the user interface is the same (i.e. creating the API client instance synchronously and calling its methods synchronously)? I have managed to create a fully async client, but this is overkill for users since it is only the get_users_info() method which benefits from asynchronous execution – I don’t want people to have to invoke async and await keywords and use context managers and all that stuff for a single HTTP request which it would be fine to be synchronous.

aiohttp may not be the best fit for your use case of mixing async with sync methods, as it’s specifically designed for asyncio use. Instead, I recommend looking into HTTPX. It has support for both sync and async Clients (similar to Sessions).

Their documentation is easy to get started with. All the best.

An alternative would be to have your aiohttp with the asynchronous operations and to build a wrap on top of it. The final interface is what your users can call synchronously, and this will handle using the client inside the calls asynchronous.

In other words this way you can benefit from asynchronous execution and still avoid users to have to invoke async and await keywords and use context managers and all that stuff.

If we have a simple aynchronous client as:

import aiohttp
import asyncio


class AsyncHttpClient:
    base_url = "https://api.example.com"
    # base_url = "http://127.0.0.1:5000" # for testing

    def __init__(self) -> None:
        self.session = None

    async def _init_session(self):
        if self.session is None:
            self.session = aiohttp.ClientSession()

    async def get_user_info(self, user_id: str) -> dict:
        await self._init_session() 
        async with self.session.get(f"{self.base_url}/users/{user_id}") as response:
            return await response.json()

    async def get_users_info(self, user_ids: list[str]) -> list[dict]:
        await self._init_session()  
        tasks = [self.get_user_info(user_id) for user_id in user_ids]
        return await asyncio.gather(*tasks)

    async def close(self):
        if self.session is not None:
            await self.session.close()

This client could be wrap into another interface that would be what your users use.

class FakeHttpClient:
    def __init__(self) -> None:
        self.async_client = AsyncHttpClient()
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

    def get_user_info(self, user_id: str) -> dict:
        return self.loop.run_until_complete(self.async_client.get_user_info(user_id))

    def get_users_info(self, user_ids: list[str]) -> list[dict]:
        return self.loop.run_until_complete(self.async_client.get_users_info(user_ids))

    def close(self):
        self.loop.run_until_complete(self.async_client.close())
        self.loop.close()

    def __del__(self):
        self.close()


if __name__ == '__main__':
    users = FakeHttpClient() .get_users_info(["1", "2", "3"])
    print(users)

Note the __del__ method into the fake client makes sure that the aiohttp.client.ClientSession is closed

For testing the code

from flask import Flask, jsonify

app = Flask(__name__)

# Sample data
users_data = {
    "1": {"id": "1", "name": "Alice", "email": "[email protected]"},
    "2": {"id": "2", "name": "Bob", "email": "[email protected]"},
    "3": {"id": "3", "name": "Charlie", "email": "[email protected]"}
}

@app.route('/users/<user_id>', methods=['GET'])
def get_user(user_id):
    print(f"User Id: {user_id}")
    user = users_data.get(user_id)
    if user:
        return jsonify(user)
    return jsonify({"error": f"User {user_id} not found"}), 404

if __name__ == '__main__':
    app.run(port=5000)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật