Random Greeting Fetcher Using httpx

  • Share this:

Code introduction


The function fetches a random greeting from a specified URL using the httpx library. It first randomly selects a greeting from a predefined list, constructs the request URL with the chosen greeting, sends an asynchronous GET request using httpx, and finally returns the response text.


Technology Stack : httpx, Python async

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import httpx
import random

def fetch_random_greeting(url):
    """
    Fetches a random greeting from a given URL using httpx.
    """
    # Randomly choose a greeting type from a predefined list
    greetings = ["hello", "hi", "greetings", "welcome"]
    greeting = random.choice(greetings)

    # Construct the request URL with the chosen greeting
    request_url = f"{url}/{greeting}"

    # Send a GET request using httpx
    async with httpx.AsyncClient() as client:
        response = await client.get(request_url)

    # Return the response text
    return response.text