Randomly Select Status Code from URL

  • Share this:

Code introduction


The function fetches the response status code from the given URL and randomly returns one. If the URL has only one status code, it returns that code directly; if the URL has multiple status codes, it randomly selects one to return.


Technology Stack : requests, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
def fetch_random_status_code(url):
    import requests
    import random

    response = requests.get(url)
    status_codes = response.status_code
    random_status_code = random.choice([status_codes] if isinstance(status_codes, int) else status_codes)

    return random_status_code