Asynchronous JSON Fetch with httpx

  • Share this:

Code introduction


This function uses the httpx library to asynchronously fetch a resource from a specified URL and returns the response content as JSON.


Technology Stack : httpx, asyncio

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import httpx
import random

def fetch_random_resource(url):
    # Fetch a random resource from the given URL using httpx
    async def fetch_resource():
        async with httpx.AsyncClient() as client:
            response = await client.get(url)
            return response.json()

    # Run the async function and return the result
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(fetch_resource())
    return result

# JSON representation of the code                
              
Tags: