Asynchronous Random Quote Fetcher

  • Share this:

Code introduction


This function fetches a random quote from a specified URL using asynchronous HTTP requests and returns it.


Technology Stack : httpx, Asynchronous programming

Code Type : Asynchronous HTTP request function

Code Difficulty : Intermediate


                
                    
import httpx
import random

def fetch_random_quote(url):
    """
    Fetch a random quote from a given URL and return it.
    """
    async def fetch_quote():
        async with httpx.AsyncClient() as client:
            response = await client.get(url)
            data = response.json()
            quote = random.choice(data['quotes'])
            return quote

    return fetch_quote()

# JSON Explanation