You can download this code by clicking the button below.
This code is now available for download.
This function generates a random user agent string and returns it in JSON format. It uses the Starlette library to create a response and Python's built-in libraries (random, string) to generate random strings.
Technology Stack : Starlette, Python built-in (random, string)
Code Type : Web API
Code Difficulty : Intermediate
def random_user_agent():
from starlette.responses import JSONResponse
import random
import string
def generate_user_agent():
# Define the parts of the user agent
user_agent_parts = [
"Mozilla/5.0",
f" ({random.choice(string.ascii_letters} {random.choice(string.digits)}.{random.choice(string.digits)}.{random.choice(string.digits)})",
"Windows NT 10.0",
"AppleWebKit/537.36",
"KHTML/537.36",
"Chrome/88.0.4324.150",
"Safari/537.36"
]
# Shuffle and join the parts to create a random user agent
random.shuffle(user_agent_parts)
return ' '.join(user_agent_parts)
# Create a JSON response with the generated user agent
return JSONResponse({"user_agent": generate_user_agent()})