1. import json
  2. from typing import Dict, Any
  3. def deserialize_api_request(request_data: str, expected_schema: Dict[str, str]) -> Dict[str, Any]:
  4. """
  5. Deserializes API request data from a string, validating against an expected schema.
  6. Args:
  7. request_data: The JSON string containing the API request data.
  8. expected_schema: A dictionary defining the expected schema for the request.
  9. Keys are field names, and values are data types (e.g., "string", "integer", "boolean", "array", "object").
  10. Returns:
  11. A dictionary representing the deserialized request data, or None if deserialization fails or validation errors occur.
  12. Raises:
  13. ValueError: If the input is not a valid JSON string.
  14. """
  15. try:
  16. data = json.loads(request_data) # Parse the JSON string
  17. except json.JSONDecodeError as e:
  18. raise ValueError(f"Invalid JSON format: {e}")
  19. validated_data = {}
  20. for field, expected_type in expected_schema.items():
  21. if field not in data:
  22. print(f"Warning: Field '{field}' missing from request data.")
  23. continue # Skip missing fields
  24. value = data[field]
  25. if expected_type == "string":
  26. if not isinstance(value, str):
  27. print(f"Error: Field '{field}' should be a string, but is {type(value)}")
  28. return None
  29. validated_data[field] = value
  30. elif expected_type == "integer":
  31. if not isinstance(value, int):
  32. try:
  33. validated_data[field] = int(value)
  34. except (ValueError, TypeError):
  35. print(f"Error: Field '{field}' should be an integer, but is {type(value)}")
  36. return None
  37. else:
  38. validated_data[field] = value
  39. elif expected_type == "boolean":
  40. if not isinstance(value, bool):
  41. if isinstance(value, str):
  42. value = value.lower()
  43. if value in ['true', '1', 't']:
  44. validated_data[field] = True
  45. elif value in ['false', '0', 'f']:
  46. validated_data[field] = False
  47. else:
  48. print(f"Error: Field '{field}' should be a boolean, but is {type(value)}")
  49. return None
  50. else:
  51. print(f"Error: Field '{field}' should be a boolean, but is {type(value)}")
  52. return None
  53. else:
  54. validated_data[field] = value
  55. elif expected_type == "array":
  56. if not isinstance(value, list):
  57. print(f"Error: Field '{field}' should be an array, but is {type(value)}")
  58. return None
  59. validated_data[field] = value
  60. elif expected_type == "object":
  61. if not isinstance(value, dict):
  62. print(f"Error: Field '{field}' should be an object, but is {type(value)}")
  63. return None
  64. validated_data[field] = value
  65. else:
  66. print(f"Warning: Unknown type '{expected_type}' for field '{field}'.")
  67. continue # Skip unknown types
  68. return validated_data

Add your comment