rsinger86 / drf-flex-fields

Dynamically set fields and expand nested resources in Django REST Framework serializers.
MIT License
740 stars 61 forks source link

Expandable Fields through SOA architecture #65

Closed Mendes11 closed 2 years ago

Mendes11 commented 3 years ago

Hi, I created an expansion from your flex fields to allow the usage between APIs.

It is really usefull in a distributed system, where we usually have many weak foreign keys that points to a resource in a different service.

The usage remained the same, so its transparent to the API consumer. It even allows the nested expand/fields/omit through APIs

Do you have interest in a PR with this feature?

Ex:

    class Meta:
        model = FileImportInput
        fields = "__all__"
        expandable_fields = {
            "data_input": (
                APIResourceFlexDict,
                {
                    "url": settings.DATA_INPUT_RESOURCE,
                    "included_headers": ["Authorization"],
                },
            ),
        }
rsinger86 commented 3 years ago

Cool! I've encountered this need before as well, but I'm wondering if the expandable_fields API would need to change or whether the remote service expansion could happen in a special serializer?

For example:

    class Meta:
        model = BlogPost
        expandable_fields = {
            "author": "RemoteServiceAuthorSerializer",
        }

class RemoteServiceAuthorSerializer(serializer.Serializer):
    def to_representation(self, remote_fk: int) -> dict:
         return remote_http_service.fetch_author(id=remote_fk)
Mendes11 commented 3 years ago

The way I did it,the library API wasn't changed at all!

Since all services are implementing the flex-fields serializers, I let the remote service handle the serializer part, and I just return the result of the API response as a DictField, so I don't need to declare the fields. But a serializer would also work, if the user desires to use some fields only (although the fields querystring in the remote service would already do that for me)

I'll see if I spare some time next month to fork this repo, implement with some tests and submit a PR... I think it is a nice feature to have here

rsinger86 commented 3 years ago

Ah, gotcha. Yeah, that sounds like a nice feature.