Minimalist example of using HTTPX library for both sync and async requests

April 23, 2024

import asyncio
import pprint
import time
 
import httpx
 
 
def fetch_joke_sync(client: httpx.Client, url: str):
    response = client.get(url)
    data = response.json()
    return data['value']
 
 
async def fetch_joke_async(client: httpx.AsyncClient, url: str):
    response = await client.get(url)
    data = response.json()
    return data['value']
 
 
def run_sync():
    url = "[https://api.chucknorris.io/jokes/random"](https://api.chucknorris.io/jokes/random")
    with httpx.Client(verify=False) as client:
        jokes = [fetch_joke_sync(client, url) for _ in range(5)]
 
    pprint.pprint(jokes)
    return None
 
 
async def run_async():
    url = "[https://api.chucknorris.io/jokes/random"](https://api.chucknorris.io/jokes/random")
    async with httpx.AsyncClient(verify=False) as client:
        tasks = [fetch_joke_async(client, url) for _ in range(5)]
        jokes = await asyncio.gather(*tasks)
 
    pprint.pprint(jokes)
    return None
 
 
if __name__ == "__main__":
    print("Starting synchronous fetching...")
    start_sync = time.time()
    run_sync()
    end_sync = time.time()
    print(f"Synchronous fetching took {end_sync - start_sync:.2f} seconds")
 
    print("\nStarting asynchronous fetching...")
    start_async = time.time()
    asyncio.run(run_async())
    end_async = time.time()
    print(f"Asynchronous fetching took {end_async - start_async:.2f} seconds")