Skip to content

✨ Enhanced Date/Time Serialization Support #10

@2-seo

Description

@2-seo

🎯 Enhancement: Automatic Date/Time Object Serialization

Issue Description

The current object serialization in FastHTTP (v0.1.1) supports Pydantic models, dataclasses, and regular classes, but lacks proper handling of date/time objects. When Pydantic models contain date, datetime, or time fields, they fail to serialize properly for JSON requests.

Problem

from datetime import date
from pydantic import BaseModel, Field
from fasthttp import FastHTTP

class ItineraryRequest(BaseModel):
    origin: str = Field(description="좜발 곡항 μ½”λ“œ")
    destination: str = Field(description="도착 곡항 μ½”λ“œ")
    departureDate: date = Field(description="좜발 λ‚ μ§œ")

http = FastHTTP(base_url="https://api.example.com")

@http.post("/bookings")
async def create_booking(response, json: ItineraryRequest = None):
    return await response.json()

itinerary = ItineraryRequest(
    origin="ICN",
    destination="NRT", 
    departureDate=date(2024, 12, 25)
)

# ❌ This fails with: Object of type date is not JSON serializable
result = await create_booking(json=itinerary)

Solution Implemented

Enhanced the to_dict() function in fasthttp/serializers.py to automatically convert date/time objects to ISO format strings:

  • date β†’ "2024-12-25" (ISO format)
  • datetime β†’ "2024-11-15T10:30:45" (ISO format)
  • time β†’ "14:30:00" (ISO format)

Changes Made

  • Added date/time object detection and conversion logic
  • Implemented recursive processing for Pydantic model_dump() results
  • Added proper handling for nested date/time objects
  • Maintained backward compatibility

Testing

βœ… Comprehensive testing completed:

  • Basic date field serialization
  • Complex models with date, datetime, and time fields
  • Optional[date] fields with None values
  • Both json and data parameter usage
  • HTTP request integration testing

Result

# βœ… Now works perfectly!
itinerary = ItineraryRequest(
    origin="ICN",
    destination="NRT", 
    departureDate=date(2024, 12, 25)
)

result = await create_booking(json=itinerary)
# Sends: {"origin": "ICN", "destination": "NRT", "departureDate": "2024-12-25"}

Impact

  • πŸš€ Zero breaking changes - fully backward compatible
  • πŸ“… Universal date/time support - handles all Python date/time types
  • πŸ”„ Consistent behavior - works for both json and data parameters
  • 🎯 Developer friendly - no manual serialization required

This enhancement significantly improves the developer experience when working with date/time fields in API requests, making FastHTTP even more intuitive and powerful.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions