Skip to content

Conversation

@KrisAt95PG
Copy link

Summary

This pull request updates the function_app.py of the MongoDB_DataAPI_Azure project to introduce an optional, environment‑controlled flag that determines whether MongoDB ObjectId values are automatically converted to strings in API responses.

Previously, all ObjectId values were converted to strings unconditionally to ensure the output was valid JSON for Azure Logic Apps and other REST clients. With this enhancement, that behavior becomes configurable - giving users flexibility depending on their downstream requirements.


Details of Changes

  • Added a new boolean configuration flag:

    ENABLE_OBJECTID_CONVERSION = os.getenv("ENABLE_OBJECTID_CONVERSION", "true").lower() == "true"
    • When true (default), all ObjectId values in responses are recursively converted to strings.
    • When false, raw BSON ObjectId objects are returned (useful for systems that can handle them natively or apply $project transformations independently).
  • Implemented a recursive helper function:

    def convert_objectid(document):
        """Recursively convert ObjectIds to strings."""
        ...
  • Updated the main response logic:

    result = convert_objectid(result)
    return success_response(result)
  • Added safe handling for nested documents and lists to ensure deep conversion.

  • Maintained existing functionality for datetime serialization via DateTimeEncoder.


Motivation

Azure Logic Apps and other HTTP clients cannot directly parse BSON ObjectId types, which causes serialization errors unless the values are first converted to strings.
However, some more advanced consumers may prefer to handle ObjectIds in Extended JSON form or internally manage conversion. This change introduces a runtime environment variable for that flexibility.


Testing

  • Default behavior (ENABLE_OBJECTID_CONVERSION=true)
    • _id fields and all nested ObjectIds are converted to strings.
    • Responses remain fully JSON serializable and compatible with Logic Apps.
  • When disabled (ENABLE_OBJECTID_CONVERSION=false)
    • The application returns ObjectId objects as-is. Useful for internal testing and advanced consumers.

Example

Set the environment variable in Azure Function configuration:

ENABLE_OBJECTID_CONVERSION=false

or in the Azure Portal → Configuration → Application Settings.


Impact

  • Backward compatible – default behavior maintains string conversion.
  • Enhanced flexibility – developers can toggle based on use case.
  • Improved maintainability – centralized recursive conversion eliminates redundant conversion logic per operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant