REST Features In WEB API With The Verbs GET, POST, PUT, DELETE, PATCH

Introduction

In this article, we will learn REST fetaures with the HTTP verbs GET, POST, PUT, DELETE and others using ASP.NET Web API. We will learn a simple example of REST Service.

Click on the given link to learn about the introduction of WebAPI - click here.

Brief definition of REST 

It bolsters traditionally based CRUD actions since it works with HTTP verbs GET, POST, PUT and DELETE. Reactions have an Accept header and HTTP status code. Reactions are organized by Web API's MediaTypeFormatter into JSON, XML or whatever organization you need to include as a MediaTypeFormatter. It might acknowledge and produce the substance which may not be protest situated like pictures, PDF documents, and so forth. It has programmed support for OData. Subsequently, by putting the new [Queryable] characteristic on a controller technique that profits IQueryable, customers can utilize the strategy for OData question structure. It can be facilitated within the applicaion or on IIS. It additionally underpins the MVC components, for example, directing, controllers, activity comes about, channel, demonstrate covers, IOC compartment, or reliance infusion that makes it more straightforward and hearty.
 

REST is frequently utilized as a part of versatile applications, long range informal communication Web locales, mashup instruments, and robotized business forms. The REST style stresses that connections amongst customers and administrations is upgraded by having a predetermined number of operations (verbs). Adaptability is given by allocating assets (things) their own particular one of a kind Universal Resource Identifiers (URIs). Since every verb has a particular importance (GET, POST, PUT and DELETE), REST stays away from equivocalness.

There are a few drawbacks. In the realm of REST, there is no immediate support for creating a customer from server-side-produced metadata. Cleanser can bolster this with Web Service Description Language (WSDL). 
 
Features of REST with example

REST normally runs over HTTP (Hypertext Transfer Protocol). It has several types of architectural constraint.
  • Stateless type
  • Enable to leverage a cache of data
  • Full leverages a layered format system
  • Full leverages a uniform data  interface
Let's see one image that gives a good explanation of HTTP verbes.

 

Now, I will show you an examples of  HTTP GET, POST, PUT, DELETE in WebAPI.
 
HTTP GET

This verb should be used only to get information or data from database or other source. The code will look like the given code.
  1.        /// <summary>  
  2.        /// Get Data from db  
  3.        /// </summary>        
  4.        /// <returns></returns>  
  5.        [HttpGet]  
  6.        [SwaggerOperation(Tags = new[] { "xyz" })]  
  7.        [Route("GetData")]  
  8.        public IHttpActionResult GetData()  
  9.        {  
  10.            var list = _provider.GetData();  
  11.   
  12.            if (list == null)  
  13.            {  
  14.                return NotFound();  
  15.            }  
  16.            return Ok(list);  
  17.        }  
Inside this code, top 1-4 number lines show swagger implimentation and after that HTTP Verb, and line number 6 displays swagger class to create folder to categorized APIs. [Route] is attribute to change endpoint via attribute routing in WebAPI and complete route will look like this. You can set RoutePrifix(/api/Dictionary/)

http://local.xxxxxxx.com/api/Dictionary/GetData

There is one more line of code that may confuse you. _provider is just a class object which is used to call in business layer. 

HTTP POST

This verb should be used only to post or create new entry with information or data to database or other source. Code will look like the given below. 
  1. /// <summary>  
  2.         /// Save data in db 
  3.         /// </summary>  
  4.         /// <param name="obj"></param>  
  5.         /// <returns></returns>  
  6.         [HttpPost]  
  7.         [SwaggerOperation(Tags = new[] { "Dictionary" })]  
  8.         [Route("SaveData")]  
  9.         public IHttpActionResult SaveData(CustomerInfo obj)  
  10.         {  
  11.            ResponseWrapper responseObj = new ResponseWrapper();  
  12.             try  
  13.             {  
  14.   
  15.                 var _result = _provider.SaveData(obj);  
  16.                 if (_result != null)  
  17.                 {  
  18.                     responseObj.status = "success";  
  19.                     responseObj.data = new { message = _result };  
  20.                 }  
  21.                 else  
  22.                 {  
  23.                     responseObj.status = "warning";  
  24.                     responseObj.data = new { message = "Operation Failed." };  
  25.                 }  
  26.             }  
  27.             catch (Exception ex)  
  28.             {  
  29.                 responseObj.status = "error";  
  30.                 responseObj.data = new { message = ex.Message };  
  31.             }  
  32.             return Ok(responseObj);  
  33.         }  
In this part of code, I have written the code to post or save data into database using REST verb HTTP POST. Final endpoint will look like the given line.

http://local.xxxxxxx.com/api/Dictionary/SaveData 

HTTP PUT

This verb should be used only to update the existing entry with information or data to database or other source. The code will look like the given code.
  1. /// <summary>  
  2.        /// Update Data.  
  3.        /// </summary>  
  4.        /// <param name="obj"></param>  
  5.        /// <returns></returns>  
  6.        [HttpPut]  
  7.        [SwaggerOperation(Tags = new[] { "Dictionary" })]  
  8.        [Route("UpdateData")]  
  9.        public IHttpActionResult UpdateData(CustomerInfo obj)  
  10.        {              
  11.            ResponseWrapper responseObj = new ResponseWrapper();  
  12.            try  
  13.            {  
  14.                var _result = _provider.UpdateData(obj);  
  15.                if (_result != null)  
  16.                {  
  17.                    responseObj.status = "success";  
  18.                    responseObj.data = new { message = _result };  
  19.                }  
  20.                else  
  21.                {  
  22.                    responseObj.status = "warning";  
  23.                    responseObj.data = new { message = "Operation Failed." };  
  24.                }  
  25.            }  
  26.            catch (Exception ex)  
  27.            {  
  28.                responseObj.status = "error";  
  29.                responseObj.data = new { message = ex.Message };  
  30.            }  
  31.            return Ok(responseObj);  
  32.        }   
In this part of code, I have written the code to update information if data is already there in database, using REST verb HTTP PUT. The final endpoint will look like the given line.

http://local.xxxxxxx.com/api/Dictionary/UpdateData

HTTP DELETE

This verb should be used only to delete existing entry within database or other source. Code will look like this. 
  1. /// <summary>  
  2.        /// Delete info.  
  3.        /// </summary>  
  4.        /// <param name="ID></param>  
  5.        /// <returns></returns>  
  6.        [HttpPut]  
  7.        [SwaggerOperation(Tags = new[] { "Client Dictionary" })]  
  8.        [Route("DeleteData/{Id}")]  
  9.        public IHttpActionResult DeleteData(int Id)  
  10.        {              
  11.            ResponseWrapper responseObj = new ResponseWrapper();  
  12.            try  
  13.            {  
  14.                var _result = _provider.DeleteData(Id);  
  15.                if (_result != null)  
  16.                {  
  17.                    responseObj.status = "success";  
  18.                    responseObj.data = new { message = _result };  
  19.                }  
  20.                else  
  21.                {  
  22.                    responseObj.status = "warning";  
  23.                    responseObj.data = new { message = "Operation Failed." };  
  24.                }  
  25.            }  
  26.            catch (Exception ex)  
  27.            {  
  28.                responseObj.status = "error";  
  29.                responseObj.data = new { message = ex.Message };  
  30.            }  
  31.            return Ok(responseObj);  
  32.        }  
In this part of code, I have written the code to delete information if data already exists in database, using REST verb HTTP DELETE. Final endpoint will look like the given line.

http://local.xxxxxxx.com/api/Dictionary/DeleteData/6

Above endpoint is passing Id as URL-encoded.

HTTP PATCH

The HTTP PATCH type should be used to update any partial resources. This verb should be used only to update the existing entry with partial data in database or other source.
  1. /// <summary>    
  2.        /// Update info.    
  3.        /// </summary>    
  4.        /// <param name="ID></param>    
  5.        /// <returns></returns>    
  6.        [HttpPatch]    
  7.        [SwaggerOperation(Tags = new[] { "Dictionary" })]    
  8.        [Route("UpdateData/{Id}")]    
  9.        public IHttpActionResult UpdateData(int Id)    
  10.        {                
  11.            ResponseWrapper responseObj = new ResponseWrapper();    
  12.            try    
  13.            {    
  14.                var _result = _provider.UpdateData(Id);    
  15.                if (_result != null)    
  16.                {    
  17.                    responseObj.status = "success";    
  18.                    responseObj.data = new { message = _result };    
  19.                }    
  20.                else    
  21.                {    
  22.                    responseObj.status = "warning";    
  23.                    responseObj.data = new { message = "Operation Failed." };    
  24.                }    
  25.            }    
  26.            catch (Exception ex)    
  27.            {    
  28.                responseObj.status = "error";    
  29.                responseObj.data = new { message = ex.Message };    
  30.            }    
  31.            return Ok(responseObj);    
  32.        }  
In this part of the code, I have written the code to update partial information if data already exists in database, using REST verb HTTP PATCH. The final endpoint will looks like the given line.

http://local.xxxxxxx.com/api/Dictionary/DeleteData/6

The above endpoint is passing Id as URL-encoded.
 
Other references

Up Next
    Ebook Download
    View all
    Learn
    View all