You can download this code by clicking the button below.
This code is now available for download.
This code defines a Falcon API that can generate a random user. The user ID is passed through the URL parameter, and the API returns a JSON object containing user information.
Technology Stack : Falcon, JSON, Python
Code Type : Web API
Code Difficulty : Intermediate
import falcon
import random
def random_user_generator(id):
"""
This function generates a random user with a given ID.
"""
users = [
{"id": 1, "name": "Alice", "email": "alice@example.com"},
{"id": 2, "name": "Bob", "email": "bob@example.com"},
{"id": 3, "name": "Charlie", "email": "charlie@example.com"}
]
user = next((user for user in users if user["id"] == id), None)
if user:
return {"user": user}
else:
return {"error": "User not found"}
api = falcon.API()
@api.route('/user/<int:id>')
def user(req, resp, id):
"""
Falcon route to handle user requests.
"""
response = random_user_generator(id)
resp.body = json.dumps(response)
resp.content_type = 'application/json'