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.

Easy Python 3.9+ Aug 9, 2026 Microservices patterns 13 views 0 copies

Python code

38 lines
Python 3.9+
import 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

stdout
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

  1. Use Pydantic's `BaseModel` for automatic validation and serialization.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Microservices patterns

Related tutorials and quizzes for this topic.