-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
π― 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
datefield serialization - Complex models with
date,datetime, andtimefields Optional[date]fields withNonevalues- Both
jsonanddataparameter 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
jsonanddataparameters - π― 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.
Reactions are currently unavailable