Random Color Selection with String Argument

  • Share this:

Code introduction


This function accepts a string argument and returns a JSON response containing a randomly selected color if the argument is valid.


Technology Stack : Starlette, JSONResponse, random

Code Type : HTTP response function

Code Difficulty : Intermediate


                
                    
def random_color(arg1):
    from starlette.responses import JSONResponse
    import random

    if not isinstance(arg1, str):
        return JSONResponse({"error": "Argument must be a string"}, status_code=400)

    colors = ["red", "green", "blue", "yellow", "purple", "orange"]
    selected_color = random.choice(colors)

    return JSONResponse({"selected_color": selected_color})