Random User Info Generator API with Starlette

  • Share this:

Code introduction


This function creates an API using the Starlette framework to randomly generate user information and return a JSON response.


Technology Stack : Starlette, JSONResponse, Request

Code Type : API Function

Code Difficulty : Intermediate


                
                    
from starlette.responses import JSONResponse
from starlette.requests import Request
import random

def random_user_info(request: Request):
    # Generate a random user info with different attributes
    gender = random.choice(["Male", "Female", "Other"])
    age = random.randint(18, 70)
    location = random.choice(["New York", "London", "Tokyo", "Paris", "Berlin"])
    hobbies = random.choice(["Reading", "Traveling", "Cooking", "Sports", "Music"])

    # Create a JSON response with the generated user info
    response = JSONResponse(
        status_code=200,
        content={"gender": gender, "age": age, "location": location, "hobbies": hobbies}
    )

    return response

# JSON explanation of the code