|
| 1 | +import json |
| 2 | +from dataclasses import dataclass |
| 3 | +from http import HTTPStatus |
| 4 | + |
| 5 | +from aws_lambda_powertools import Logger |
| 6 | +from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response |
| 7 | +from aws_lambda_powertools.utilities.typing import LambdaContext |
| 8 | + |
| 9 | +logger = Logger() |
| 10 | + |
| 11 | +# This would likely be a db lookup |
| 12 | +users = [ |
| 13 | + { |
| 14 | + "user_id": "b0b2a5bf-ee1e-4c5e-9a86-91074052739e", |
| 15 | + |
| 16 | + "active": True, |
| 17 | + }, |
| 18 | + { |
| 19 | + "user_id": "3a9df6b1-938c-4e80-bd4a-0c966f4b1c1e", |
| 20 | + |
| 21 | + "active": False, |
| 22 | + }, |
| 23 | + { |
| 24 | + "user_id": "aa0d3d09-9cb9-42b9-9e63-1fb17ea52981", |
| 25 | + |
| 26 | + "active": True, |
| 27 | + }, |
| 28 | +] |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class User: |
| 33 | + user_id: str |
| 34 | + email: str |
| 35 | + active: bool |
| 36 | + |
| 37 | + |
| 38 | +def get_user_by_id(user_id: str) -> Union[User, None]: |
| 39 | + for user_data in users: |
| 40 | + if user_data["user_id"] == user_id: |
| 41 | + return User( |
| 42 | + user_id=str(user_data["user_id"]), |
| 43 | + email=str(user_data["email"]), |
| 44 | + active=bool(user_data["active"]), |
| 45 | + ) |
| 46 | + |
| 47 | + return None |
| 48 | + |
| 49 | + |
| 50 | +app = APIGatewayRestResolver() |
| 51 | + |
| 52 | + |
| 53 | +@app.get("/users/<user_id>") |
| 54 | +def all_active_users(user_id: str): |
| 55 | + """HTTP Response for all active users""" |
| 56 | + user = get_user_by_id(user_id) |
| 57 | + |
| 58 | + if user: |
| 59 | + return Response( |
| 60 | + status_code=HTTPStatus.OK.value, |
| 61 | + content_type="application/json", |
| 62 | + body=json.dumps(user.__dict__), |
| 63 | + ) |
| 64 | + |
| 65 | + else: |
| 66 | + return Response(status_code=HTTPStatus.NOT_FOUND) |
| 67 | + |
| 68 | + |
| 69 | +@logger.inject_lambda_context() |
| 70 | +def lambda_handler(event: dict, context: LambdaContext) -> dict: |
| 71 | + return app.resolve(event, context) |
0 commit comments