Skip to main content
coding intermediate

Implement Data Serialization for APIs

Generate complete data serialization code for APIs. Handles JSON, XML, binary formats with validation, error handling, and best practices.

Works with: chatgptclaudegemini

Prompt Template

You are an expert backend developer specializing in data serialization for APIs. I need you to implement a complete data serialization solution with the following specifications: **Requirements:** - Programming language: [PROGRAMMING_LANGUAGE] - Serialization format: [SERIALIZATION_FORMAT] - Data structure to serialize: [DATA_STRUCTURE] - Target use case: [USE_CASE] **Implementation Requirements:** 1. Create serialization and deserialization functions/methods 2. Include comprehensive error handling for malformed data 3. Add data validation before serialization 4. Implement proper type checking and conversion 5. Handle edge cases (null values, empty objects, circular references) 6. Add performance optimizations where applicable 7. Include unit tests for the implementation 8. Add clear documentation and usage examples **Additional Considerations:** - Follow language-specific best practices and conventions - Ensure the code is production-ready and maintainable - Include proper logging for debugging purposes - Consider memory efficiency for large datasets - Implement version compatibility if relevant **Deliverables:** 1. Complete serialization class/module with methods 2. Error handling classes/functions 3. Validation utilities 4. Unit tests covering normal and edge cases 5. Usage examples with sample data 6. Performance benchmarks if applicable Provide clean, well-commented code that follows SOLID principles and includes proper documentation for each method.

Variables to Customize

[PROGRAMMING_LANGUAGE]

The programming language to implement the serialization in

Example: Python

[SERIALIZATION_FORMAT]

The data format for serialization (JSON, XML, Protocol Buffers, etc.)

Example: JSON

[DATA_STRUCTURE]

The specific data structure or model to serialize

Example: User profile with nested address and preferences objects

[USE_CASE]

The specific use case or context for the serialization

Example: REST API responses for a user management system

Example Output

```python import json import logging from typing import Dict, Any, Optional from dataclasses import dataclass, asdict from datetime import datetime @dataclass class Address: street: str city: str country: str postal_code: str @dataclass class UserProfile: user_id: int username: str email: str address: Address preferences: Dict[str, Any] created_at: datetime class UserProfileSerializer: """Handles serialization/deserialization of UserProfile objects for REST API responses""" def __init__(self): self.logger = logging.getLogger(__name__) def serialize(self, user_profile: UserProfile) -> str: """Serialize UserProfile to JSON string""" try: self._validate_user_profile(user_profile) # Convert to dictionary with datetime handling data = asdict(user_profile) data['created_at'] = user_profile.created_at.isoformat() return json.dumps(data, ensure_ascii=False, indent=2) except Exception as e: self.logger.error(f"Serialization failed: {str(e)}") raise SerializationError(f"Failed to serialize user profile: {str(e)}") def deserialize(self, json_data: str) -> UserProfile: """Deserialize JSON string to UserProfile object""" try: data = json.loads(json_data) # Reconstruct nested objects address = Address(**data.pop('address')) created_at = datetime.fromisoformat(data.pop('created_at')) return UserProfile( address=address, created_at=created_at, **data ) except json.JSONDecodeError as e: raise DeserializationError(f"Invalid JSON format: {str(e)}") except Exception as e: raise DeserializationError(f"Failed to deserialize: {str(e)}") ```

Pro Tips for Best Results

  • Specify your exact data models and their relationships to get more accurate serialization code
  • Include information about required validation rules to get proper error handling implementation
  • Mention performance requirements if dealing with large datasets to get optimized solutions
  • Request specific error handling scenarios based on your API's needs
  • Ask for integration examples with your existing framework (Django, Flask, FastAPI, etc.)

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like