How to Implement a Data Helper for Microservices in Python
Create a reusable helper class to serialize, deserialize, and wrap data for microservice communication using dataclasses and JSON.
Python code
38 linesimport json
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class ServiceResponse:
status: str
data: Any
message: str = ""
class DataHelper:
"""Simple helper for microservice data handling."""
@staticmethod
def serialize(data: Dict[str, Any]) -> str:
return json.dumps(data)
@staticmethod
def deserialize(data: str) -> Dict[str, Any]:
return json.loads(data)
@staticmethod
def wrapper_response(data: Any, status: str = "success") -> ServiceResponse:
return ServiceResponse(status=status, data=data)
if __name__ == "__main__":
payload = {"user_id": 42, "name": "Alice", "roles": ["admin"]}
serialized = DataHelper.serialize(payload)
print("Serialized:", serialized)
deserialized = DataHelper.deserialize(serialized)
print("Deserialized:", deserialized)
response = DataHelper.wrapper_response(deserialized)
print("Response:", asdict(response))
Output
Serialized: {"user_id": 42, "name": "Alice", "roles": ["admin"]}
Deserialized: {'user_id': 42, 'name': 'Alice', 'roles': ['admin']}
Response: {'status': 'success', 'data': {'user_id': 42, 'name': 'Alice', 'roles': ['admin']}, 'message': ''}
How it works
The DataHelper class groups static methods for common JSON operations, making it easy to reuse in different parts of your microservice. serialize uses json.dumps to convert a dictionary to a JSON string, while deserialize reverses it with json.loads. The ServiceResponse dataclass provides a consistent structure for service responses, and asdict converts it back to a plain dictionary for easier logging or transmission. Using a dataclass ensures type hints and reduces boilerplate code.
Common mistakes
- Using `json.dumps` on non-serializable objects like datetimes without a custom encoder.
- Forgetting to handle JSON decode errors when input is malformed.
- Assuming `asdict` preserves nested dataclasses as dictionaries — it does, but only for supported types.
Variations
- Use Pydantic's `BaseModel` for automatic validation and serialization.
- Add custom JSON encoder for datetimes or Decimal objects.
Real-world use cases
- Serializing request payloads when calling another microservice's REST API.
- Deserializing webhook responses before processing business logic.
- Wrapping service results in a standard response envelope for consistent API responses.
Sponsored
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Consumer Driven Contract Pact Mock in Python medium
Keep learning
Related tutorials and quizzes for this topic.