Random JSON Response Web API with Starlette

  • Share this:

Code introduction


This function uses the Starlette library to create a simple Web API that randomly returns different JSON responses.


Technology Stack : Starlette

Code Type : Web API

Code Difficulty : Intermediate


                
                    
from starlette.responses import JSONResponse
from starlette.routing import Route, Routes
import random

def random_route_handler(request):
    # Generate a random number to select a function from a predefined list
    choice = random.randint(0, 2)
    if choice == 0:
        return JSONResponse({"message": "Hello, World!"})
    elif choice == 1:
        return JSONResponse({"status": "OK"})
    elif choice == 2:
        return JSONResponse({"error": "Not Found"})

def create_route():
    # Define a list of possible responses
    responses = [
        lambda request: JSONResponse({"message": "Hello, World!"}),
        lambda request: JSONResponse({"status": "OK"}),
        lambda request: JSONResponse({"error": "Not Found"})
    ]
    
    # Randomly select a response function
    response_function = random.choice(responses)
    
    # Create a single route that uses the selected response function
    route = Route(path="/random", endpoint=response_function)
    return route

def xxx(request):
    # Create a list of routes
    routes = [create_route() for _ in range(3)]
    
    # Create a router with the list of routes
    router = Routes(*routes)
    
    # Return the response from the router
    return router(request)

# Code Information                
              
Tags: