Async Random User Fetch with httpx

  • Share this:

Code introduction


This function sends an asynchronous HTTP GET request to https://randomuser.me/api/ using the httpx library. This API returns a JSON object containing randomly generated user information. The function checks the HTTP response status code, and if successful (status code 200), it returns the JSON response; otherwise, it returns None.


Technology Stack : httpx

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
import httpx
import random

def fetch_random_user():
    url = "https://randomuser.me/api/"
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        if response.status_code == 200:
            return response.json()
        else:
            return None

# JSON Response                
              
Tags: