In this article, we are going to talk about a neat concept called data shaping and how to implement it in ASP.NET Core Web API. To achieve that, we are going to use similar tools as we did in the sorting article. Data shaping is not something that every API needs, but it can be very useful in some cases.

If you want to follow along with the article, you can use the start branch and if you want to get the final solution or if you get stuck, switch to the final branch.

NOTE: Some degree of previous knowledge is needed to follow this article. It relies heavily on the ASP.NET Core Web API series on Code Maze, so if you are not sure how to set up the database or how the underlying architecture works, we strongly suggest you go through the series.

In this article we are going to learn:

Let’s start by learning what data shaping is exactly.

What is Data Shaping

Data shaping is a great way to reduce the amount of traffic sent from the API to the client. It enables the consumer of the API to select (shape) the data by choosing the fields through the query string.

What we mean by this is something like:

This would tell the API to return a list of owners with ONLY the Name and DateOfBirth fields of the owner entity. In our case, the owner entity doesn’t have too many fields to choose from, but you can see how this can be very helpful when an entity has a lot of fields in it. It’s not that uncommon.

By giving the consumer a way to select just the fields it needs, we can potentially reduce the stress on the API. On the other hand, this is not something that every API needs, so we need to think carefully and decide whether we should implement its implementation has a bit of reflection going on.

And we know for a fact that reflection takes its toll and slows our application down.

Finally, as always, data-shaping should work well together with the concepts we’ve covered so far – paging, filtering, searching, and sorting.

Let’s get to work.

How to Implement Data Shaping in ASP.NET Core Web API

First things first, we need to extend our QueryStringParameters class since we are going to add a new feature to our query string and we want it to be available for any entity:

We’ve added the Fields property and now we can use fields as a query string parameter.

Next on, similarly to what we did with sorting, we are going to do here. But, we’ll make this generic to start with.

We’ll make the IDataShaper.cs and DataShaper.cs in the Helpers folder of the Entities project:

First, let’s create the IDataShaper interface:

The IDataShaper defines two methods that should be implemented, one for the single entity, and one for the collection of entities. Both are named ShapeData but they have different signatures.

Notice how we use the ExpandoObjecttype as a return type. We need to do that in order to shape our data how we want it.

And now, let’s see the actual implementation:

Let’s break this class down.

Implementation – Step by Step

We have one public property in this class – Properties. It’s an array of PropertyInfo’s that we’re going to pull out of the input type, whatever it is, Account or Owner in our case.

So here it is, on class instantiation, we get all the properties of an input class.

Next on, we have the implementation of our two public methods ShapeData:

They both look similar and rely on the GetRequiredProperties method to parse the input string that contains the fields we want to fetch.

The GetRequiredProperties method is a method that does the magic. It parses the input string and returns just the properties we need to return to the controller:

As you can see, there’s nothing special about it. If the fieldsString is not empty, we split it and check if the fields match the properties in our entity. If they do, we add them to the list of required properties.

On the other hand, if the fieldsString is empty, we consider all properties are required.

Now, FetchData and FetchDataForEntity are the private methods to extract the values from these required properties we’ve prepared:

FetchDataForEntity does it for a single entity:

As you can see, we loop through the requiredProperties and then using a bit of reflection, we extract the values and add them to our ExpandoObject. ExpandoObject implements IDictionary<string,object> so we can use the TryAdd method to add our property using its name as a key, and the value as a value for the dictionary.

This way we dynamically add just the properties we need to our dynamic object.

The FetchData method is just an implementation for multiple objects. It utilizes the FetchDataForEntity method we’ve just implemented:

Nothing special here, just looping through the list of entities and returning a collection of shaped entities as a result.

That’s it for the implementation, let’s see how do we connect all this into our existing solution.

Connecting the Dots

Now that we’ve implemented the logic we can inject our data shaper in the repositories as we did with ISortHelper:

And then apply data shaping in the GetOwners method:

Create another GetOwnerById method that shapes the data since we still need our regular method for validation checks in the controller actions:

And don’t forget to modify the IOwnerRepository interface to reflect these changes:

You can try changing AccountRepository on your own for practice. If you get stuck, check out the finished project.

And of course, since we’ve modified the repository classes constructors, we need to modify our RepositoryWrapper too:

Using dependency injection means we need to register our data shapers in the ConfigureRepositoryWrapper method of the ServiceExtensions class order to resolve them:

And because we’ve done such an awesome job, we don’t need to change our GetOwners action in the OwnerController, but we do need to make a slight change to validation in the GetOwnerById action:

As you can see the changes aren’t that drastic.

Everything is set up now. We just need to run this and it will work for sure. Or will it?

As a matter of fact, it won’t 🙂

Resolving Json Serialization Problems

Now, if we try to run the application as it is right now, we will get a big fat InvalidCastException. The reason for that is that System.Text doesn’t support the casting of ExpandoObject to IDictionary, which is what we need to happen when we return the result from the controller.

To avoid this, we need to add Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and then in the ConfigureServices method of our Startup.cs class find the services.AddControllers() line and add .AddNewtonsoftJson()method to the end of it:

What this does is replace the default System.Text.Json serializer with Newtonsoft.Json one. The exception should be gone now and the application should work normally again.

While we are at it, we are going to configure the application to respect browser headers, return 406 Not Acceptable if an unknown media type is requested, and use a data contract XML serializer because we want to support content negotiation.

This solves the problem with the json serialization.

But let’s test our solution, to see if it actually does what we specified.

Testing Our Solution

Before we test our solution, let’s quickly take a look at how our Owner table looks like right now:

database owners extended

Great, these entries should do it.

First, let’s send a plain GET request to our owners’ endpoint:

We should get a full response back:

So our data shaping functionality hasn’t changed the default application behavior.

Now, let’s see data shaping in action:

The API should return the shaped data:

And now to top it off, let’s see if it works with paging, filtering, searching and sorting:
https://localhost:5001/api/owner?fields=name,dateOfBirth&pageSize=2&pageNumber=1&orderBy=name asc,dateOfBirth desc&maxYearOfBirth=1970

This query should return only one result. Can you guess which one? If you’ve guessed, leave us a comment with what you think the result is.

That’s it, we’ve tested our API successfully.

One more thing to test. Let’s try to request an XML result.

Resolving XML Serialization Problems

Let’s change the Accept header to application/xml and send a request. We want to test out if our content negotiation works.

We are going to send a simple request this time:

And the response looks like this:

As you can see that looks pretty ugly and unreadable. But that’s how our XmlDataContractSerializerOutputFormatter serializes our ExpandoObject by default.

So do we want to fix this and how do we do it?

This is a topic that’s quite outside of the scope of this article, but you can find the solution in the finished project source code.

A simple explanation is that we need to create our own dynamic object and define XML serialization rules for it.

So we need to create something like this:

The main thing to notice here is that we inherit from DynamicObject that will make our object dynamic, IXmlSerializable interface, which we need to implement custom serialization rules and IDictionary<string, object> because of the Add method that is needed for XML serialization.

All that’s left is to replace the ExpandoObject type to the Entity type throughout our project.

Now, we should get a response like this one:

That looks much nicer, doesn’t it?

If the XML serialization is not important to you, you can keep using ExpandoObject, but if you want a nicely formatted XML response, this is a way to go.

Ok, let’s summarize what we’ve done so far.


Data shaping is an exciting and neat little feature that can really make our APIs flexible and reduce our network traffic. If we have a high volume traffic API, data shaping should work just fine. On the other hand, it’s not a feature that we should use lightly because it utilizes reflection and dynamic typing to get things done.

As with all other functionalities, we need to be careful when and if we should implement data shaping. Performance tests might come in handy even if we do implement it.

In this article we’ve covered:

  • What data shaping is
  • How to implement a generic data shaping solution in ASP.NET Core Web API
  • How to fix our json serialization problems with ExpandoObject
  • Testing of our solution by sending some simple requests
  • Formatting our XML responses

If you found some parts unclear, we suggest taking a quick look at the other parts of this mini-series: paging, filtering, searching, and sorting. Paging article is especially important since we set up the infrastructure for the whole series in that article.

Hopefully, you’ve learned something new and interesting this time.