<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>REST on Journey through Cloud &amp; Code</title><link>https://gurupasupathy.com/tags/rest/</link><description>Recent content in REST on Journey through Cloud &amp; Code</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Thu, 25 Nov 2021 00:00:00 +0000</lastBuildDate><atom:link href="https://gurupasupathy.com/tags/rest/index.xml" rel="self" type="application/rss+xml"/><item><title>Reducing Data Transfer Objects using Tuples in C#</title><link>https://gurupasupathy.com/post/2021-11-25_reducing-data-transfer-objects-using-tuples/</link><pubDate>Thu, 25 Nov 2021 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2021-11-25_reducing-data-transfer-objects-using-tuples/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="https://gurupasupathy.com/img/1__o63lCwtjwCbbGw__KrUl__sw.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;I have come across quite a few ASP.NET Core WebAPI solutions where there is a inordinate number of Data Transfer Object (&lt;a href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&amp;amp;tabs=visual-studio#prevent-over-posting-1"&gt;DTO&lt;/a&gt;) classes. This results in a kind of class explosion which I think can be avoided. Yes, DTOs do have their utility, no doubt. But, many a times as the application evolves and grows, we often end up with numerous DTOs and these DTOs sometimes differ just by a handful of attributes or in some cases they are a simple composition of multiple entities / DTOs.&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="/img/1__o63lCwtjwCbbGw__KrUl__sw.jpeg"></p>
<p>I have come across quite a few ASP.NET Core WebAPI solutions where there is a inordinate number of Data Transfer Object (<a href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&amp;tabs=visual-studio#prevent-over-posting-1">DTO</a>) classes. This results in a kind of class explosion which I think can be avoided. Yes, DTOs do have their utility, no doubt. But, many a times as the application evolves and grows, we often end up with numerous DTOs and these DTOs sometimes differ just by a handful of attributes or in some cases they are a simple composition of multiple entities / DTOs.</p>
<p>One of the reasons we have so many such DTO classes is the need to pass data to and from repository and service layer ( between different layers of the application for that matter). In order to find a way around creating yet another DTO, I was exploring some options and realized that Tuples can be used to minimize the creation of DTOs</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples">Tuples</a> have been around in C# for quite sometime now. I am not sure if it is a common knowledge but I recently figured out that you could eliminate quite a few DTOs that we use to ferry data between the layers by leveraging Tuples</p>
<p>Let us take the following scenario of instance.</p>
<p>We have an API, say, GetCustomers which, <em>of course</em>, will return me the list of customers . And, we have an entity, Customer as defined below.</p>
<p>class Customer<br>
{<br>
public int customerId {get; set;}<br>
public string firstname {get; set;}<br>
public string lastname {get; set;}<br>
}</p>
<p>The API response for our GetCustomers API is as below</p>
<p>You would have noticed that the attribute <em>count</em> is expected in the response and this is not present in our Customer class. The repository layer would just return a List<Customer> but the service layer needs to pass it along with the <em>count</em> attribute to the controller. This is usually where we tend to create a DTO as below.</p>
<p>class CustomerDTO<br>
{<br>
int count;<br>
List<Customer> customers<br>
}</p>
<p>The only reason for the above class to exist is to ferry the data from repository in a format that the controller is expecting. We can eliminate this class altogether by returning Tuple as below</p>
<p>return new Tuple&lt;int, List<Customer>&gt;(result.Count,result)</p>
<p>Granted, this is a very trivial scenario and you can add the count attribute in the controller and return an anonymous type also.</p>
<p>Now consider the cases when you need a response that is aggregation of multiple custom types. For instance, if we have two API one to get customer and another to get order details we would have created two DTO for Customer and Order. If a new API is required that gives details pertaining to a particular Customer and all related Orders as response, you might have to create a new DTO again, as below.</p>
<p>public class newDTO {<br>
public int orderCount {get; set;}<br>
public int customerId {get; set;}<br>
public List<Order> orders {get; set;}<br>
}</p>
<p>The expected response is</p>
<p>This is exactly what we can avoid by using Tuples like below in the service and repository layer.</p>
<p>RepositoryLayer.cs</p>
<p>var <strong>repoResponse</strong> = new Tuple&lt;int, Customer customer, List<Order>&gt;(count,custResult, orderResult);<br>
return <strong>repoResponse</strong>;</p>
<p><em>custResult holds a particular customer’s data and orderResult will be a List<Order></em></p>
<p>ServiceLayer.cs</p>
<p>.<br>
.<br>
.<br>
<em>//Create a Tuple with three members, count, customer and orders <br>
//repoResponse is the response from your repository(a Tuple)</em><br>
(int count, Customer customer, List<Order> orderList) <strong>result</strong> = (<strong>repoResponse</strong>.Item1,    <strong>repoResponse</strong>.Item2, <strong>repoResponse</strong>.Item3);</p>
<p>return <strong>result</strong>;<br>
}</p>
<p>From the above service response, the controller can create an anonymous type as below without ever creating a DTO and return the <a href="https://gist.github.com/gurupasupathy/4d04d8352e9b2be63cee00bcfea6a3fc">response</a> .</p>
<p>return new { ordercount= <strong>serviceResponse</strong>.count, customer = <strong>serviceResponse</strong>.customer.customerId, serviceResponse = <strong>serviceResponse</strong>.orderList };</p>
<p>It should be noted that, although this approach eliminates the need to create DTO classes, it come at the cost of readability. Your method signatures may not be very elegant and readable. While DTOs will still be the right way to go in some scenarios, for others, Tuples can help.</p>
<p>Hope this helps in reducing a few DTOs at your end.</p>
<p>Cheers!</p>
]]></content:encoded></item><item><title>How I ended up writing cleaner PATCH calls using JSON Patch</title><link>https://gurupasupathy.com/post/2020-07-05_patch-calls-using-json-patch/</link><pubDate>Mon, 06 Jul 2020 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2020-07-05_patch-calls-using-json-patch/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="https://gurupasupathy.com/img/1__a__P3zmoCIshJqSyuAQQGeA.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;I have written my fair share of RESTful API but am no expert by any measure. I had never given enough thought about the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods"&gt;HTTP Verbs&lt;/a&gt; I should be using (like, PUT, POST, PATCH) while writing API. If a resource had to be created, I would automatically go for POST (_never considered the idempoten_cy &lt;em&gt;angle at all&lt;/em&gt;) and if a resource had to be modified, I would go for PATCH.&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="/img/1__a__P3zmoCIshJqSyuAQQGeA.jpeg"></p>
<p>I have written my fair share of RESTful API but am no expert by any measure. I had never given enough thought about the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">HTTP Verbs</a> I should be using (like, PUT, POST, PATCH) while writing API. If a resource had to be created, I would automatically go for POST (_never considered the idempoten_cy <em>angle at all</em>) and if a resource had to be modified, I would go for PATCH.</p>
<p>On one of my API assignments, I decided to make a very conscious and deliberated choice of the verbs I will be using; and an API in particular got me thinking.</p>
<p>I had to write an API to modify a resource and this resource happened to have nested resources and numerous attributes. I soon realized that it wasn’t so straight forward to create an elegant PATCH API due to the sheer number of attributes on this resource that can potentially get modified (<em>Why did you design a resource with so many attributes in the first place? you might ask. But that is a topic for another day</em>)</p>
<p>So, coming back to the task in hand, I was aware of only two choices to go about writing a PATCH call. Either, send just the attributes requiring modifications to the API (<em>Approach 1</em>) or end the entire resource to API <em>after</em> making changes to the necessary attributes at consumers’ end (<em>Approach 2</em>). We will examine both the approaches in the context of the below two classes (Employee and Address)</p>
<pre><code>    public class Employee  
    {  
        public int EmployeeId {get; set;}  
        public string EmployeeName {get; set;}  
        public Address EmployeeAddress {get; set;}  
        public string WorkLocation {get; set;}  
        public List&lt;string&gt; PreferredWorkLocations {get; set;}

    }

    public class EmployeeAddress  
    {  
        public string HouseNumber {get; set;}  
        public string AddressLine1 {get; set;}  
        public string AddressLine2 {get; set;}  
    }
</code></pre>
<p><strong><em>Approach 1:</em></strong> The consumer of the PATCH API will send the entire resource, after changing a few select attribute that need to be modified. At the API end, the PATCH payload will be handed over to the repository layer which would then update the entire resource to the database. Other than some basic validations, no additional work is needed at the API end. A sample PATCH call (<em>almost a PUT</em>) would look like below</p>
<pre><code>    **api/ModifyEmployee/{empId}  
    **{  
    &quot;EmployeeName&quot; : &quot;ename&quot;,  
    &quot;EmployeeAddress&quot; : {  
                &quot;HouseNumber&quot; : &quot;F32&quot;,  
                &quot;AddressLine1&quot; : &quot;Addr1&quot;,  
                &quot;AddressLine2&quot; : &quot;Addr2&quot;  
                },  
    &quot;WorkLocation&quot; : &quot;Brazil&quot;,  
    &quot;PreferredWorkLocations&quot; : \[&quot;Brazil&quot;,&quot;France&quot;\]  
    }
</code></pre>
<blockquote>
<p>Downside: the consumer has to build the entire object even if only a single attribute requires modification. Also note that, there is no way of knowing if just the “houseNumber” has changed or any other / all the attributes of Employee has changed. So, all the attributes’ values need to be copied back to a new object object to be persisted in the database.</p>
</blockquote>
<p><strong><em>Approach 2:</em></strong> The consumer of the API will send only the attribute that had to be modified. A sample PATCH for modifying the work location will look like below:</p>
<pre><code>    **api/ModifyEmployeeWorkLocation/{empId}  
    **{  
    &quot;WorkLocation&quot; : &quot;Brazil&quot;  
    }
</code></pre>
<blockquote>
<p>Downside: the onus of constructing an object that can be handed over to the repository layer falls on the API service layer (an object mapper need to be used here)</p>
</blockquote>
<blockquote>
<p>Further, this approach might necessitates that a new API be created of each combination of possible modifications in the resource attributes. Consider if I have to update the Employee Address I will have to have another method like api/ModifyEmployeeAddress/{empId}. If the class has many attributes that could be modified this can lead to explosion of PATCH methods.</p>
</blockquote>
<h3 id="json-patch"><strong>JSON Patch</strong></h3>
<p>Neither of the approaches appealed to me. This is when I stumbled upon JSON PATCH. Honestly, I had never heard of JSON Patch before and wanted to give it a shot as I thought it would address the downsides mentioned above.</p>
<p>What I like the most about JSON Patch was that <strong><em>as a consumer</em></strong> I don’t have to send the entire object as payload for the PATCH call, I can just mention what operation (<em>add / remove / replace / copy</em>) I want to perform on which resource attribute / subset of attributes. Also, <strong><em>at the API end</em></strong>, I there is not need to have multiple methods for each type of modifications and there is no need to manually copy over the incoming values to a new object that the repository will understand and persist</p>
<p>Using JSON Patch, these call can be as simple as below</p>
<pre><code>    **\[    
        {**  
            &quot;**value**&quot;: &quot;address line one&quot;,  
            &quot;**path**&quot;: &quot;/address/addressLine1&quot;,  
            &quot;**op**&quot;: &quot;replace&quot;  
        **}  
    \]**
</code></pre>
<p>The advantage of using JSON Patch is that you don’t have to reconstruct the object at your API end. You can use a middle-ware like NewtonsoftJsonPatch and simply use <strong><em>ApplyTo</em></strong> method to construct the object for persistence / further processing.</p>
<pre><code>    public async Task&lt;IActionResult&gt; UpdateEmployee(\[FromBody\] **JsonPatchDocument&lt;Employee&gt;** patchDoc, int empId)  
    {  
        if (patchDoc != null)  
        {  
            var emp = await &lt;yourCache&gt;.GetAsync&lt;Employee&gt;(&quot;cacheKey&quot;);

            if (emp == null)   
            {  
                emp = await yourService.GetEmployeeData(empId);  
            }

            **patchDoc.ApplyTo(emp, ModelState);**

            //call repository to update.   
            \_ = await yourService.UpdateAsync(emp);

            return new ObjectResult(emp);  
        }  
        else  
        {  
            return BadRequest(ModelState);  
        }  
    }
</code></pre>
<p>The ApplyTo method will take care of copying (or performing any operation based on the value supplied in “op” attribute of the PATCH call) the new values to the existing object. This eliminates the need to do this mapping and copying manually using a mapper.</p>
<p>Another plus is that you don’t have to have multiple PATCH calls for each of the attributes, you can club multiple modification requests in the same PATCH call like below. Please note that you have to use /- notation to add to a list.</p>
<pre><code>    \[  
    {  
            &quot;value&quot;: &quot;new work Location&quot;,  
            &quot;path&quot;: &quot;/preferredWorkLocations/-&quot;,  
            &quot;op&quot;: &quot;add&quot;  
    },  
    {  
            &quot;value&quot;: &quot;address line one&quot;,  
            &quot;path&quot;: &quot;/address/addressLine1&quot;,  
            &quot;op&quot;: &quot;replace&quot;  
    }  
    \]
</code></pre>
<p>You may refer to the below link for detailed information on how to use JSON Patch in ASP.NET Core.</p>
<p><a href="https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1" title="https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1"><strong>JsonPatch in ASP.NET Core web API</strong><br>
_By Tom Dykstra and Kirk Larkin This article explains how to handle JSON Patch requests in an ASP.NET Core web API. To…_docs.microsoft.com</a><a href="https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1"></a></p>
<p>So, that’s how I embraced JSON Patch.</p>
<p>Cheers!</p>
]]></content:encoded></item></channel></rss>