Conditional Serialization of Api Response Fields
Know a days we all work on SaaS product and whenever we develop something, we make sure this should be generic for all our customers. Multiple times we have situation where we are developing API which will consume by multiple customers but all the fields available to API response might not be useful for all the customers. So some customer would need few fields and some customer few other fields and if we develop API which return all the fields either those fields are relevant to all customer or not then this will have bad experience for the customer to see/consume all the fields even which they do not require.
To void this, we must do conditional serialization of API response model properties.
"NewtonSoft" provide "ShouldSerialize" method which can do this for you. Let see how you can achieve this practically -
I have created test API in .net core:
Here if you see, I have created API response model "Result" class and there mainly I have two properties "CustomerA" and "CustomerB" which will return in API response but I want to return "CustomerA" only when customer "A" request receive in API as query string value and similarly return "CustomerB" only when customer "B" request receive in API as query string value. And to achieve this I have created two additional properties against each API response property in "Result" API response model class i.e.
- "CustomerAToReturn" which is getting set true false in API action method as per query string value received.
- "ShouldSerializeCustomerA" where "ShouldSerialize" is NetonSoft method and "CustomerA" is your property name which will return in API response. So "ShouldSerialize" method tells the compiler to serialize the property based on value true false set for this method.
Register "Netonsoft" serialization dependency -
Now when I test my API and pass query string value as "A" then it return only "CustomerA" property in response-
Additional Info : If you are creating API in .net framework then you have to register "Netonsoft" serialization dependency into API config file like below -
Categories/Tags: Conditional Serialization