├── .gitignore ├── LICENSE ├── README.md ├── async_api_caller ├── __init__.py └── async_api_caller.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Amentum Scientific 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # async_api_caller 2 | 3 | Making asynchronous web API calls using asyncio is pretty complicated. This package abstracts away complexity for the common case of needing to make multiple web API calls while varying query parameters. 4 | 5 | ## Installation 6 | 7 | Clone this repo, then: 8 | 9 | ```bash 10 | cd async_api_caller/ 11 | pip install . 12 | ``` 13 | 14 | ## Usage 15 | 16 | ```Python 17 | import async_api_caller 18 | url = "https://ocean.amentum.io/gebco" 19 | headers = {'API-Key': API_KEY} 20 | param_list = [ 21 | { 22 | "latitude": 42, 23 | "longitude": 42 24 | },{ 25 | "latitude": 43, 26 | "longitude": 43 27 | } 28 | ] 29 | 30 | responses_json = async_api_caller.run( 31 | url, headers, param_list 32 | ) 33 | ``` 34 | 35 | ## Caching 36 | 37 | To avoid making duplicate API calls to metered APIs, responses are automatically cached in a sqlite database `cache.db`. Delete the file to refresh it. 38 | 39 | ## Sponsor 40 | 41 | [Amentum Scientific](https://amentum.io) 42 | 43 | -------------------------------------------------------------------------------- /async_api_caller/__init__.py: -------------------------------------------------------------------------------- 1 | from .async_api_caller import run -------------------------------------------------------------------------------- /async_api_caller/async_api_caller.py: -------------------------------------------------------------------------------- 1 | import aiohttp 2 | import asyncio 3 | import json 4 | import hashlib 5 | from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn 6 | import sqlite3 7 | import numpy as np 8 | 9 | class SQLiteCache: 10 | def __init__(self, db_name='cache.db'): 11 | self.conn = sqlite3.connect(db_name) 12 | self.create_table() 13 | 14 | def create_table(self): 15 | with self.conn: 16 | self.conn.execute(''' 17 | CREATE TABLE IF NOT EXISTS cache ( 18 | key TEXT PRIMARY KEY, 19 | value TEXT, 20 | expires_at INTEGER 21 | ) 22 | ''') 23 | 24 | def get(self, key): 25 | cur = self.conn.cursor() 26 | cur.execute('SELECT value, expires_at FROM cache WHERE key=?', (key,)) 27 | row = cur.fetchone() 28 | if row: 29 | value, expires_at = row 30 | if expires_at is None or expires_at > int(asyncio.get_event_loop().time()): 31 | return json.loads(value) 32 | return None 33 | 34 | def set(self, key, value, ttl=None): 35 | expires_at = int(asyncio.get_event_loop().time()) + ttl if ttl else None 36 | with self.conn: 37 | self.conn.execute(''' 38 | REPLACE INTO cache (key, value, expires_at) 39 | VALUES (?, ?, ?) 40 | ''', (key, json.dumps(value), expires_at)) 41 | 42 | def clear(self): 43 | with self.conn: 44 | self.conn.execute('DELETE FROM cache WHERE expires_at IS NOT NULL AND expires_at <= ?', (int(asyncio.get_event_loop().time()),)) 45 | 46 | def close(self): 47 | self.conn.close() 48 | 49 | 50 | def make_values_json_serializable(d): 51 | return {key: make_json_serializable(value) for key, value in d.items()} 52 | 53 | def make_json_serializable(value): 54 | if isinstance(value, np.integer): 55 | return int(value) 56 | elif isinstance(value, np.floating): 57 | return float(value) 58 | elif isinstance(value, np.ndarray): 59 | return value.tolist() # Convert NumPy arrays to lists 60 | elif isinstance(value, (np.bool_, bool)): 61 | return bool(value) # Ensure boolean types are handled 62 | elif isinstance(value, (np.str_, str)): 63 | return str(value) 64 | else: 65 | return value 66 | 67 | # Function to create a hash for the cache key 68 | def hash_key(url, params): 69 | # required for numpy types in param list 70 | params_serialisable = make_values_json_serializable(params) 71 | params_json = json.dumps(params_serialisable, sort_keys=True) 72 | key = f"{url}_{params_json}" 73 | return hashlib.md5(key.encode()).hexdigest() 74 | 75 | # Makes the API call asynchronously 76 | async def fetch_data(session, url, params=None, headers=None, cache=None, ttl=360000): 77 | 78 | # return cached response if present 79 | key = hash_key(url, params) 80 | if cache: 81 | cached_response = cache.get(key) 82 | if cached_response: 83 | return params, cached_response 84 | try: 85 | async with session.get(url, params=params, headers=headers) as resp: 86 | resp.raise_for_status() # Raises an exception for HTTP errors 87 | response_json = await resp.json() 88 | if cache: 89 | cache.set(key, response_json, ttl) 90 | return params, response_json 91 | except aiohttp.ClientError as e: 92 | print(f"Request failed: {e}") 93 | return params, None 94 | 95 | # A function that receives a url, header, and list of params that vary 96 | async def main(url, headers, param_list): 97 | cache = SQLiteCache() # Initialize the custom SQLite cache 98 | async with aiohttp.ClientSession() as session: 99 | with Progress( 100 | SpinnerColumn(), 101 | "[progress.description]{task.description}", 102 | BarColumn(), 103 | "[progress.percentage]{task.percentage:>3.0f}%", 104 | TextColumn("[bold blue]{task.completed}/{task.total}") 105 | ) as progress: 106 | 107 | task = progress.add_task("Fetching data", total=len(param_list)) 108 | 109 | tasks = [] 110 | for params in param_list: 111 | tasks.append(asyncio.create_task(fetch_data(session, url, params, headers, cache))) 112 | 113 | for task_future in asyncio.as_completed(tasks): 114 | _ = await task_future 115 | progress.update(task, advance=1) 116 | 117 | # Reorder according to original param_list 118 | sorted_result = sorted(tasks, key=lambda x: param_list.index(x.result()[0])) 119 | 120 | # Extract the sorted responses now 121 | responses = [r.result()[1] for r in sorted_result if r.result()[1] is not None] 122 | 123 | return responses 124 | 125 | def run(url, headers, param_list): 126 | return asyncio.run(main(url, headers, param_list)) 127 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="async_api_caller", 8 | version="0.2.0", 9 | author="https://amentum.io", 10 | author_email="team@amentum.space", 11 | description="Easily make asynchronous API web calls in Pythons", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/amentumspace/async_api_caller.git", 15 | packages=setuptools.find_packages(), 16 | install_requires=['aiohttp', 'asyncio', 'rich', 'numpy'], 17 | ) 18 | 19 | --------------------------------------------------------------------------------