You can download this code by clicking the button below.
This code is now available for download.
This Starlette-based Web API function handles different HTTP request paths and performs different operations based on the path, such as summing numbers and converting strings to uppercase.
Technology Stack : Starlette, JSONResponse, Request
Code Type : Web API Function
Code Difficulty : Intermediate
from starlette.responses import JSONResponse
from starlette.requests import Request
import random
def random_starlette_function(request: Request):
# Generate a random response based on the request's path
path = request.path
if path.startswith('/add'):
# Create a JSON response with the sum of two numbers
numbers = request.query_params.getall('number')
try:
sum_result = sum(map(int, numbers))
return JSONResponse(content={"sum": sum_result})
except ValueError:
return JSONResponse(content={"error": "Invalid input"}, status_code=400)
elif path.startswith('/uppercase'):
# Convert a string to uppercase
text = request.query_params.get('text', '')
return JSONResponse(content={"uppercase": text.upper()})
else:
# Return a simple JSON response for any other path
return JSONResponse(content={"message": "Hello, World!"})