import json
from typing import Dict, Any
def deserialize_api_request(request_data: str, expected_schema: Dict[str, str]) -> Dict[str, Any]:
"""
Deserializes API request data from a string, validating against an expected schema.
Args:
request_data: The JSON string containing the API request data.
expected_schema: A dictionary defining the expected schema for the request.
Keys are field names, and values are data types (e.g., "string", "integer", "boolean", "array", "object").
Returns:
A dictionary representing the deserialized request data, or None if deserialization fails or validation errors occur.
Raises:
ValueError: If the input is not a valid JSON string.
"""
try:
data = json.loads(request_data) # Parse the JSON string
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON format: {e}")
validated_data = {}
for field, expected_type in expected_schema.items():
if field not in data:
print(f"Warning: Field '{field}' missing from request data.")
continue # Skip missing fields
value = data[field]
if expected_type == "string":
if not isinstance(value, str):
print(f"Error: Field '{field}' should be a string, but is {type(value)}")
return None
validated_data[field] = value
elif expected_type == "integer":
if not isinstance(value, int):
try:
validated_data[field] = int(value)
except (ValueError, TypeError):
print(f"Error: Field '{field}' should be an integer, but is {type(value)}")
return None
else:
validated_data[field] = value
elif expected_type == "boolean":
if not isinstance(value, bool):
if isinstance(value, str):
value = value.lower()
if value in ['true', '1', 't']:
validated_data[field] = True
elif value in ['false', '0', 'f']:
validated_data[field] = False
else:
print(f"Error: Field '{field}' should be a boolean, but is {type(value)}")
return None
else:
print(f"Error: Field '{field}' should be a boolean, but is {type(value)}")
return None
else:
validated_data[field] = value
elif expected_type == "array":
if not isinstance(value, list):
print(f"Error: Field '{field}' should be an array, but is {type(value)}")
return None
validated_data[field] = value
elif expected_type == "object":
if not isinstance(value, dict):
print(f"Error: Field '{field}' should be an object, but is {type(value)}")
return None
validated_data[field] = value
else:
print(f"Warning: Unknown type '{expected_type}' for field '{field}'.")
continue # Skip unknown types
return validated_data
Add your comment