Threads

mail@pastecode.io avatar
unknown
python
7 months ago
871 B
1
Indexable
Never
import concurrent.futures
import requests


def api_request(url):
    try:
        response = requests.get(url)
        return response.text
    except requests.exceptions.RequestException:
        return None


def call_external_apis(api_urls, max_workers=100):
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        results = list(executor.map(api_request, api_urls))

    return results


if __name__ == "__main__":
    api_urls = [
                   "https://jsonplaceholder.typicode.com/posts/1",
                   "https://jsonplaceholder.typicode.com/posts/2",
                   "https://jsonplaceholder.typicode.com/posts/3",
               ] * 33

    results = call_external_apis(api_urls, max_workers=100)

    for url, result in zip(api_urls, results):
        print(f"API URL: {url}\nResponse: {result}\n{'-' * 30}")
Leave a Comment