Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Monday, June 7, 2021

Difference between Put and Patch

 

What is PUT?

PUT is a method of modifying resource where the client sends data that updates the entire resource. It is used to set an entity’s information completely. PUT is similar to POST in that it can create resources, but it does so when there is a defined URI. PUT overwrites the entire entity if it already exists, and creates a new resource if it doesn’t exist.

For example, when you want to change the first name of a person in a database, you need to send the entire resource when making a PUT request.

{“first": "John", "last": "Stone”}

To make a PUT request, you need to send the two parameters; the first and the last name.

What is PATCH?

Unlike PUT, PATCH applies a partial update to the resource.

This means that you are only required to send the data that you want to update, and it won’t affect or change anything else. So if you want to update the first name on a database, you will only be required to send the first parameter; the first name.

Source : https://rapidapi.com/blog/put-vs-patch/


Friday, June 4, 2021

Difference between REST and RESTfull services

 

REST based Services/Architecture vs. RESTFUL Services/Architecture

To differentiate or compare these 2, you should know what REST is.

REST (REpresentational State Transfer) is basically an architectural style of development having some principles:

  • It should be stateless

  • It should access all the resources from the server using only URI

  • It does not have inbuilt encryption

  • It does not have session

  • It uses one and only one protocol - HTTP

  • For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete

  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )

REST based services follow some of the above principles and not all

RESTFUL services means it follows all the above principles.

It is similar to the concept of:

Object oriented languages support all the OOP concepts, examples: C++, C#

Object-based languages support some of the OOP features, examples: JavaScript, VB



Source : https://stackoverflow.com/questions/1568834/whats-the-difference-between-rest-restful

Thursday, June 3, 2021

Change Data Capture

 Change data capture (CDC) is a software process or technology that identifies and tracks changes to data stored in a database, such as inserts, updates, and deletes. While a database is useful for storing the latest state of data, CDC preserves the various states of data over time by providing an audit trail, and it can provide incremental changes to other repositories or applications.

In a very basic example, CDC enables you in December of a given year to look up your home address as of January, even if you had moved in between, and your address in the database reflects the current value.


How Does Change Data Capture Work?


CDC delivers data on records that changed for database functions such as inserts, updates, and deletes, and makes a record of that change available either within a database itself or to other applications that rely on the data. CDC tools typically rely on the database’s transaction log, which keeps track internally of record changes for the purposes of system recovery. CDC tools leverage that information to deliver database changes to an external system.


What Are Common Methods of Change Data Capture?

There are different approaches that a system can use to capture changes in data. The use of timestamps is one of the most popular methods of CDC, as most systems track when a row was created and most recently modified.

Database transaction logs are also a resource for CDC. Log scanners can identify any changes in these transaction logs. As long as the log scanner can interpret the log, this can be an ideal solution for CDC because it has little impact on the underlying database, delivers changes with low latency, and ensures transaction integrity because every change is tracked in order.

As event streaming has gained popularity, so has the use of the publish/subscribe model of CDC, where a database triggers log or publish change events to a table and shares those changes with the CDC system. The series of updates that CDC delivers looks like a stream of data, making stream processing engines (like Hazelcast Jet) a suitable technology for consuming CDC data.







Thursday, March 14, 2019

OverrideFiter

Override filter used to skip global and controller level filter fom action method with the help of OverrideAuthorize.

Friday, February 22, 2019

Docker

A container can be thought of as a really lightweight VM.

Containers are much smaller than VMs by default — a container doesn't contain a full operating system, whereas a VM does. Containers thus require a lot less in terms of processing power in order to run — they tend to be mere megabytes in size and take just seconds to start.

VMs tend to be gigabytes in size and can take minutes to start, because operating systems are big! Containers make use of libraries and packages on the host operating system in order to access resources. They then make use of their own libraries and packages in order to emulate separate operating systems, as needed, instead of installing unnecessary bloat. For example, you could run an Ubuntu image on your Windows machine without needing to install Ubuntu.

The smallness of containers is, of course, really great when it comes to scaling applications. If we were hosting recommend_service as a VM and had a spike in traffic, users would just have to deal with some extra latency and perhaps some errors while we brought extra VMs online. On the other hand, if we were using containers, we would be able to bring them online much faster, and potentially even keep extra instances running, in case of spikes, because containers are cheap.

Docker is the de facto industry standard container platform.

Docker allows the creation of images. Images are instantiated to create containers (if you are familiar with object orientated programming, then images are like classes, and containers are like objects). In this section, we will create and run a container, and the container will contain a service we wish to deploy.

Microservice

Microservices are a way of breaking large software projects into loosely coupled modules, which communicate with each other through simple Application Programming Interfaces (APIs).

Resilience : the capacity to recover quickly from difficulties
Improve fault isolation: Larger applications can remain mostly unaffected by the failure of a single module.

Technology Heterogeneity
Eliminate vendor or technology lock-in: You can try new technolgy with different module.

Ease of Understanding: With added simplicity, developers can better understand the functionality of a service.

Scaling
With a large, monolithic service, we have to scale everything together. One small part of our overall system is constrained in performance, but if that behavior is locked up in a giant monolithic application, we have to handle scaling everything as a piece. With smaller services, we can just scale those services that need scaling, allowing us to run other parts of the system on smaller, less powerful hardware.

Ease of Deployment
A one-line change to a million-line-long monolithic application requires the whole application to be deployed in order to release the change. That could be a large-impact, high-risk deployment. In practice, large-impact, high-risk deployments end up happening infrequently due to understandable fear.

With microservices, we can make a change to a single service and deploy it independently of the rest of the system. This allows us to get our code deployed faster. If a problem does occur, it can be isolated quickly to an individual service, making fast rollback easy to achieve.

Composability
One of the key promises of distributed systems and service-oriented architectures is that we open up opportunities for reuse of functionality. With microservices, we allow for our functionality to be consumed in different ways for different purposes. This can be especially important when we think about how our consumers use our software.

Optimizing for Replaceability : Easy to replace it needed.With our individual services being small in size, the cost to replace them with a better implementation, or even delete them altogether, is much easier to manage.

Deployment of Microservices

The best way to deploy microservices-based applications is within containers, which are complete virtual operating system environments that provide processes with isolation and dedicated access to underlying hardware resources. One of the biggest names in container solutions right now is Docker,


Drawback of Microservices

Large numbers of microservices are difficult to orchestrate.
Understanding, managing and testing dependencies is difficult.
Message flow increases with the number of microservices and hampers performance.
Large numbers of microservices are difficult to secure.
Once requirements change, do you want a microservice for one new feature or re-write and add to an existing service. That is a difficult decision in an architecture with many microservices.

Wednesday, December 19, 2018

Disadvantage of Cookies

Cookies enable you to store the session information on the client side which has the following advantages,

• Persistence: One of the most powerful aspects of cookies is their persistence. When a cookie is set on the client's browser, it can persist for days, months or even years. This makes it easy to save user preferences and visit information and to keep this information available every time the user returns to your site. Moreover, as cookies are stored on the client's hard disk so if the server crashes they are still available.

• Transparent: Cookies work transparently without the user being aware that information needs to be stored.

• They lighten the load on the server's memory.

 Disadvantages of Cookies

The following are the disadvantages of cookies :

• Sometimes clients disable cookies on their browsers in response to security or privacy worries which will cause problem for web applications that require them.

• Individual cookie can contain a very limited amount of information (not more than 4 kb).

• Cookies are limited to simple string information. They cannot store complex information.

• Cookies are easily accessible and readable if the user finds and reopens.

• Most browsers restrict the number of cookies that can be set by a single domain to not more than20 cookies (except Internet Explorer). If you attempt to set more than 20 cookies, the oldest cookies are automatically deleted.

Friday, December 14, 2018

HTTP Cookies in Web API

A cookie is controlled by some attribute set in the cookie header, these attributes are as follows:

Domain: It is the specified domain that is receives the cookie. If the domain is not specified then the domain is the origin server.

Path: It specifies the limit in the domain if the path is not specify then it uses the URI path.

Expires: It specifies the date/time when the cookie will be expire, the user can delete the cookie when it has expired.

Max-age: It is a numeric value that specifies the timespan of the cookie that includes the life of the cookie. It can be deleted if it reaches its maximum age like as "expires" does.

Web API and Cookies

We know that the Web API creates services over the HTTP. It can be a web page for making AJAX requests, it can be a native app for retrieving the data or it can be a headless bot for pooling the data. The Web API does the work over the HTTP and the cookie is the part of the HTTP.

Setting a Cookie with multiple values

public HttpResponseMessage Get() 
{ 
HttpResponseMessage respMessage = new HttpResponseMessage(); 
respMessage.Content = new ObjectContent(new string[] 
{ 
  "value1", 
  "value2" 
}, new JsonMediaTypeFormatter()); 
var nvc = new NameValueCollection(); 
nvc["sessid"] = "1234"; 
nvc["3dstyle"] = "flat"; 
nvc["theme"] = "red"; 
var cookie = new CookieHeaderValue("session", nv); 
cookie.Expires = DateTimeOffset.Now.AddDays(1); 
cookie.Domain = Request.RequestUri.Host; 
cookie.Path = "/"; 
respMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 
return respMessage; 
} 


https://www.devcurry.com/2013/04/http-cookies-and-aspnet-web-api.html

Http message handlers in Web API

A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.


Server-Side Message Handlers
On the server side, the Web API pipeline uses some built-in message handlers:

HttpServer gets the request from the host.
HttpRoutingDispatcher dispatches the request based on the route.
HttpControllerDispatcher sends the request to a Web API controller.
You can add custom handlers to the pipeline. Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might:

Read or modify request headers.
Add a response header to responses.
Validate requests before they reach the controller.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

Exception in Web API

Summary
We can use HttpResponseException when the possibility of exception is known by us. In the above example, we have thrown exception using HttpResponseException class as we know there is a chance to employee not found in the database.

We can use exception filter to catch unhandled exceptions on action/controllers.

We can use Exception Handlers to catch any type of unhandled exception application-wide.

Detail

There are many ways to handle the exception. 

Using HttpResponseException

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor. 

For example, the following method of EmployeeController returns Status code 404 (not found), if employee data is not found for ID.

public Employee Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
  
    if (data == null)  
    {  
        var response = new HttpResponseMessage(HttpStatusCode.NotFound)  
        {  
            Content = new StringContent(string.Format("No Employee found with ID = {0}", key)),  
                ReasonPhrase = "Employee Not Found"  
        };  
  
        throw new HttpResponseException(response);  
    }  
    return data;  
} 

Using HttpError

CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client. CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.
public HttpResponseMessage Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
    if (data == null)  
    {  
        string message = string.Format("No Employee found with ID = {0}", key);  
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);  
    }  
    return Request.CreateResponse(HttpStatusCode.OK, data);;  
}  

Using Exception Filters

Exception filters can be used to handle unhandled exceptions which are generated in Web API. The exception filter can be able to catch the unhandled exceptions in Web API. This filter is executed when an action method throws the unhandled exception. Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response.

namespace WebAPITest  
{  
    using System.Net;  
    usingSystem.Net.Http;  
    usingSystem.Web.Http.Filters;  
  
    public class CustomExceptionFilter: ExceptionFilterAttribute  
    {  
        public override void OnException(HttpActionExecutedContextactionExecutedContext)  
        {  
            string exceptionMessage = string.Empty;  
            if (actionExecutedContext.Exception.InnerException == null)  
            {  
                exceptionMessage = actionExecutedContext.Exception.Message;  
            }  
            else  
            {  
                exceptionMessage = actionExecutedContext.Exception.InnerException.Message;  
            }  
            //We can log this exception message to the file or database.  
            var response = newHttpResponseMessage(HttpStatusCode.InternalServerError)  
            {  
                Content = newStringContent(“An unhandled exception was thrown by service.”),  
                    ReasonPhrase = "Internal Server Error.Please Contact your Administrator."  
            };  
            actionExecutedContext.Response = response;  
        }  
    }  
}  


Register Exception Filters

Decorate Action with exception filter.
Decorate Controller with exception filter.
Filter Register globally.

To apply the exception filter to all Web API controllers, the filter needs to register to GlobalConfiguration.Configuration.Filters collection.
public static class WebApiConfig  
{  
    public static void Register(HttpConfigurationconfig)  
    {  
        config.Filters.Add(newCustomExceptionFilter());  
    }  
}  

Using Exception Handlers

Normally, exception filter is used to catch the unhandled exception. This approach will work fine but it fails if any error is raised from outside action. For example, if any error is raised in the following area then exception filter will not work.
Error inside the exception filter.
Exception related to routing.
Error inside the Message Handlers class.
Error in Controller Constructor.


https://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/

Modify Header in Web API

You will need to create a custom filter and apply that to your controller .
public class CustomHeaderFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       var count = actionExecutedContext.Request.Properties["Count"];
       actionExecutedContext.Response.Content.Headers.Add("totalHeader", count);
    }
}

How to make Post Cacheable?

Being cacheable is one of architectural constraints of REST. GET requests should be cachable by default – until special condition arises. Usually, browsers treat all GET requests cacheable. POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.
There are two main HTTP response headers that we can use to control caching behavior:

Expires

The Expires HTTP header specifies an absolute expiry time for a cached representation. Beyond that time, a cached representation is considered stale and must be re-validated with the origin server. To indicate that a representation never expires, a service can include a time up to one year in the future.
Expires: Fri, 20 May 2016 19:20:49 IST

Cache-Control

The header value comprises one or more comma-separated directives. These directives determine whether a response is cacheable, and if so, by whom, and for how long e.g. max-age or s-maxage directives.
Cache-Control: max-age=3600
Cacheable responses (whether to a GET or to a POST request) should also include a validator — either an ETag or a Last-Modified header.

ETag

An ETag value is an opaque string token that a server associates with a resource to uniquely identify the state of the resource over its lifetime. When the resource changes, the ETag changes accordingly.
ETag: "abcd1234567n34jv"

Last-Modified

Whereas a response’s Date header indicates when the response was generated, the Last-Modified header indicates when the associated resource last changed. The Last-Modified value cannot be later than the Date value.

Source : https://restfulapi.net/caching/


So let’s say that the client sends a request for some metadata, and we want the client to cache it for 1 hour:
GET /customers/metadata HTTP/1.1
Host: api.example.com
Accept: application/json
Accept-Language: en
To do this, we just add the Cache-Control header to our response:
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600
Content-Length: 88
Etag: "6d82cbb050ddc7fa9cbb659014546e59"

{
  "languageCodes": [
    {"da":"Danish"},
    {"no":"Norwegian"},
    {"en":"English"}
  ]
}
Source: https://www.kennethlange.com/boost-your-rest-api-with-http-caching/

Caching in Web API

Caching is a technique of storing frequently used data or information in a local memory, for a certain time period. So, next time, when the client requests the same information, instead of retrieving the information from the database, it will give the information from the local memory.

By default get is not cacheable, you need to make it using Action Filter

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net.Http.Headers;  
using System.Web;  
using System.Web.Http.Filters;  
  
namespace Caching_In_API  
{  
    public class CacheFilter : ActionFilterAttribute  
    {  
        public int TimeDuration { get; set; }  
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)  
    {  
        actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue  
        {  
            MaxAge = TimeSpan.FromSeconds(TimeDuration),  
            MustRevalidate = true,  
            Public = true  
        };  
    }  
    }  
} 


https://www.c-sharpcorner.com/article/implementing-caching-in-web-api/

What are resource in Web API

Ques :
Is the following URL a resource? If it is, what is the name of that resource and what is its representation?
The GET response of the URL should look something like:
[
   {
      id: 6,
      name: "John"
   },
   {
      id: 7,
      name: "Jane"
   }
]

Ans:

REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON.

Representation of Resources

A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format.
For example, in RESTful Web Services - First Application chapter, a user is a resource which is represented using the following XML format −
 
   1
Mahesh Teacher
The same resource can be represented in JSON format as follows −
{ 
   "id":1, 
   "name":"Mahesh", 
   "profession":"Teacher" 
}

Source : https://www.tutorialspoint.com/restful/restful_resources.htm

The URL is never a resource or its name or its representation.
URL just tells where the resource is located and You can invoke GET,POST,PUT,DELETE etc on this URL to invoke the resource.
Data responded back are the resources while the form of the data is its representation.
Let's say Your URL with given GET parameters can output a JSON resource - this is the JSON representation of this resource. While with other flag in the GET it could respond with the same data in XML - that will be another representation of the very same resource.
Another definition
Also the resource name is considered to be the 'script name', e.g. in this case it is users.jsonwhile this resource name is self describing the resource representation itself - when calling this resource we expect the resource is in JSON, while when calling e.g. users.xml we would expect the data in XML.
  1. When I change the offset parameter in GET the response contains different data set - is it a new resource or its representation?
  2. When I define which columns are returned in response in GET, is it a different resource or different representation, or?
  1. Well, here the problem and answer are clear - we still call the same URL, the server responses with the data in the same form (still it is JSON), data still contains information about users - just the information itself has changed due to the new offset parameter. So it is obvious that it is still the same resource with the same representation and the same resource name as before.
  2. Second problem could be a little confusing. Though we are calling the same resource, though the resource contains the same data (just with only predefined column set) and though the data is in the same representation it could seem to us as a different resource. But due to the points in the paragraph above it is nor the different resource or different representation. Though the data set contains less information the requesting side (filtering this data set) should be considering this and behave accordingly. So again: it is the same resource with the same resource name and the same resource representation.

Followers

Link