I have built a basic c# webapi application that returns JSON.
My system will have a number of classes, I will use cars as an example.
I have an abstract class called Car that has many different types of cars that inherit from the Car. Examples would be Truck, Sedan, Limo, Bulldozer, Ambulance, etc. These all have some additional properties.
Everything in my app is working as expected, but when I query /api/Cars/ and get back all cars, I might get something like this:
{
"Id": 6290,
"Make": "GM",
"Model": "Yukon",
"Seats": 7
},
{
"Id": 6291,
"Make": "Caterpillar",
"Model": "D11T",
"BucketWidth": 14.5
},
{
"Id": 6292,
"Make": "Braun",
"Model": "Express",
"Siren": "ACME"
}
So, as the person consuming this, how do they know that the first item is an SUV, the second is a Bulldozer, and the 3rd an ambulance?
Do I add a property to the base class called "CarType" that they would use conditionally to map it to a class on their end?
You can use the DTO Pattern to merge all the properties that you want to expose from web API to the client.
In your case can do this: 1- Create a CarDto class (you can use anohter name if you prefer) with all the properties that you want to expose 2 - Create a List of type CarDto which will be filled with your data 3 - Replace your cars result with the cars dto result.
I hope this will helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With