Random API Quote Fetcher using httpx

  • Share this:

Code introduction


This function randomly selects one of the three APIs and uses the httpx library to asynchronously request a random quote or fact, returning the JSON response.


Technology Stack : Python, httpx

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import httpx
import random

def fetch_random_quote():
    urls = [
        "https://api.quotable.io/random",
        "https://api.factstream.org/random",
        "https://api.darksky.net/forecast/your_api_key/latitude,longitude"
    ]
    chosen_url = random.choice(urls)
    async with httpx.AsyncClient() as client:
        response = await client.get(chosen_url)
        if response.status_code == 200:
            return response.json()
        else:
            return {"error": "Failed to fetch data"}

# JSON output                
              
Tags: