Random Sanic Endpoint Generator

  • Share this:

Code introduction


This function creates a simple API endpoint using the Sanic library, returning different responses based on different HTTP request methods.


Technology Stack : Sanic

Code Type : Sanic Endpoint Function

Code Difficulty : Intermediate


                
                    
import random

def random_sanic_function():
    # Randomly select a Sanic endpoint function
    def random_endpoint(request):
        # Randomly choose a request method
        method = random.choice(["GET", "POST", "PUT", "DELETE", "PATCH"])
        # Randomly choose a response content
        content = random.choice(["Hello World!", "Welcome to the API!", "This is a test response."])
        # Return a response based on the chosen method
        if method == "GET":
            return {"message": content}
        elif method == "POST":
            return {"status": "POST request received", "message": content}
        elif method == "PUT":
            return {"status": "PUT request received", "message": content}
        elif method == "DELETE":
            return {"status": "DELETE request received", "message": content}
        elif method == "PATCH":
            return {"status": "PATCH request received", "message": content}

    return random_endpoint

# Code JSON Explanation                
              
Tags: