|
| 1 | +import json |
| 2 | +import os |
| 3 | +import uuid |
| 4 | +from decimal import Decimal |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import boto3 |
| 8 | +from botocore.exceptions import ClientError |
| 9 | + |
| 10 | +from aws_lambda_powertools import Logger |
| 11 | +from aws_lambda_powertools.event_handler import ( |
| 12 | + APIGatewayRestResolver, |
| 13 | + Response, |
| 14 | + content_types, |
| 15 | +) |
| 16 | +from aws_lambda_powertools.event_handler.exceptions import BadRequestError, NotFoundError |
| 17 | +from aws_lambda_powertools.logging import correlation_paths |
| 18 | +from aws_lambda_powertools.utilities.typing import LambdaContext |
| 19 | + |
| 20 | +logger = Logger(level=os.getenv("LOG_LEVEL", "INFO")) |
| 21 | +app = APIGatewayRestResolver() |
| 22 | + |
| 23 | +table_name = os.environ["CAR_TABLE_NAME"] |
| 24 | +dynamodb = boto3.resource("dynamodb") |
| 25 | +table = dynamodb.Table(table_name) |
| 26 | + |
| 27 | +def _json_default(value: Any) -> Any: |
| 28 | + if isinstance(value, Decimal): |
| 29 | + if value % 1 == 0: |
| 30 | + return int(value) |
| 31 | + return float(value) |
| 32 | + raise TypeError(f"Object of type {type(value)} is not JSON serializable") |
| 33 | + |
| 34 | + |
| 35 | +def _json_body() -> dict: |
| 36 | + """Parse request body as JSON object; empty or missing body returns {}.""" |
| 37 | + raw = app.current_event.json_body |
| 38 | + if raw is None: |
| 39 | + return {} |
| 40 | + if not isinstance(raw, dict): |
| 41 | + raise BadRequestError("Request body must be a JSON object") |
| 42 | + return raw |
| 43 | + |
| 44 | + |
| 45 | +@app.post("/cars") |
| 46 | +def create_car() -> Response: |
| 47 | + body = _json_body() |
| 48 | + car_id = str(uuid.uuid4()) |
| 49 | + car = { |
| 50 | + "id": car_id, |
| 51 | + "make": body.get("make"), |
| 52 | + "model": body.get("model"), |
| 53 | + "year": body.get("year"), |
| 54 | + "color": body.get("color"), |
| 55 | + } |
| 56 | + table.put_item(Item=car) |
| 57 | + return Response( |
| 58 | + status_code=201, |
| 59 | + content_type=content_types.APPLICATION_JSON, |
| 60 | + body=json.dumps(car, default=_json_default), |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +@app.get("/cars/<car_id>") |
| 65 | +def get_car(car_id: str) -> Response: |
| 66 | + item = table.get_item(Key={"id": car_id}).get("Item") |
| 67 | + if not item: |
| 68 | + raise NotFoundError(f"Car with id {car_id} not found") |
| 69 | + return Response( |
| 70 | + status_code=200, |
| 71 | + content_type=content_types.APPLICATION_JSON, |
| 72 | + body=json.dumps(item, default=_json_default), |
| 73 | + ) |
| 74 | + |
| 75 | + |
| 76 | +@app.put("/cars/<car_id>") |
| 77 | +def update_car(car_id: str) -> Response: |
| 78 | + body = _json_body() |
| 79 | + existing = table.get_item(Key={"id": car_id}).get("Item") |
| 80 | + if not existing: |
| 81 | + raise NotFoundError(f"Car with id {car_id} not found") |
| 82 | + updated = { |
| 83 | + "id": car_id, |
| 84 | + "make": body.get("make", existing.get("make")), |
| 85 | + "model": body.get("model", existing.get("model")), |
| 86 | + "year": body.get("year", existing.get("year")), |
| 87 | + "color": body.get("color", existing.get("color")), |
| 88 | + } |
| 89 | + table.put_item(Item=updated) |
| 90 | + return Response( |
| 91 | + status_code=200, |
| 92 | + content_type=content_types.APPLICATION_JSON, |
| 93 | + body=json.dumps(updated, default=_json_default), |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +@app.delete("/cars/<car_id>") |
| 98 | +def delete_car(car_id: str) -> Response: |
| 99 | + try: |
| 100 | + table.delete_item( |
| 101 | + Key={"id": car_id}, |
| 102 | + ConditionExpression="attribute_exists(id)", |
| 103 | + ) |
| 104 | + except ClientError as exc: |
| 105 | + if exc.response["Error"]["Code"] == "ConditionalCheckFailedException": |
| 106 | + raise NotFoundError(f"Car with id {car_id} not found") from exc |
| 107 | + raise |
| 108 | + return Response(status_code=204, body="") |
| 109 | + |
| 110 | + |
| 111 | +@app.exception_handler(NotFoundError) |
| 112 | +def handle_not_found(exc: NotFoundError) -> Response: |
| 113 | + return Response( |
| 114 | + status_code=404, |
| 115 | + content_type=content_types.APPLICATION_JSON, |
| 116 | + body=json.dumps({"message": str(exc)}), |
| 117 | + ) |
| 118 | + |
| 119 | + |
| 120 | +@app.exception_handler(BadRequestError) |
| 121 | +def handle_bad_request(exc: BadRequestError) -> Response: |
| 122 | + return Response( |
| 123 | + status_code=400, |
| 124 | + content_type=content_types.APPLICATION_JSON, |
| 125 | + body=json.dumps({"message": str(exc)}), |
| 126 | + ) |
| 127 | + |
| 128 | + |
| 129 | +@app.not_found |
| 130 | +def handle_route_not_found(_exc: Exception) -> Response: |
| 131 | + return Response( |
| 132 | + status_code=404, |
| 133 | + content_type=content_types.APPLICATION_JSON, |
| 134 | + body=json.dumps({"message": "Route not found"}), |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST) |
| 139 | +def handler(event: dict, context: LambdaContext) -> dict: |
| 140 | + return app.resolve(event, context) |
0 commit comments