Ability To Develop HTTP Methods Or Verbs (GET, POST, PUT, DELETE etc)

Before going to explain the significant verbs or methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE and CONNECT) for the communication among different clients and servers, first of all, we should understand what are HTTP methods? and how they are useful in real time.

What are HTTP Methods?

When a browser submits a request to a server, the request contains some part of an HTTP related information. The requested part is what the client would like the server to do some action with the specified resource. The HTTP methods represents those actions.

Example

  • Retrieve specific data from a server (GET, HEAD)
  • Submit data to a server (POST)
  • Update data in a data source (PUT)
  • Delete an item from the server’s data source (DELETE)

When implementing these HTTP methods, we should be aware that the software represents the user in their actions and allows the user to be aware of any actions they might take have an unexpected significance to themselves or others.

It is not possible to ensure that the server doesn’t generate any side effects as a result while performing a request. Basically, the end user did not request the side effects. So, they cannot be held accountable for them.

First, we have to understand one of the important properties of these methods before going too much deeper into these verbs or methods. i.e “Idempotent”.property.

What is Idempotent?

A sequence that never has side effects is called idempotent. That means no concurrent operations are being executed on the same set of resources. Methods can also have the property of “idempotence”. The methods GET, HEAD, PUT and DELETE have this property. The side effects of ‘N’ number of identical requests is the same as for a single request. And the methods OPTIONS and TRACE should not have side effects.

Now, let's move on to the actual HTTP methods for getting a clear picture on what we are talking about.

HTTP GET

The GET method is used to retrieve data from a server using a given requested URI. The GET method should only retrieve data and should have no other impact on the data.

Example

For better understanding, I implemented GET method in Web API Controller using Entity Framework.

  1. public class EmployeeController : ApiController  
  2.       {  
  3.             
  4.           [HttpGet]  
  5.           public IHttpActionResult GetAllEmployees(){  
  6.               using (var context = new EmployeeDBEntities())  
  7.               {  
  8.                   employees = context.Employees  
  9.                               .Select(e => new EmployeeViewModel()  
  10.                               {  
  11.                                   Id = e.EmpID,  
  12.                                   FirstName = e.EmployeeName,  
  13.                                   Designation = e.Designation  
  14.                   }).ToList<EmployeeViewModel>();  
  15.               }  
  16.   
  17.               if (employees.Count == 0)  
  18.               {  
  19.                   return NotFound();  
  20.               }  
  21.   
  22.               return Ok(employees);  
  23.           }  
  24.       }  

The above example GetAllEmployees() method returns all the employees using EF. If no employee exists, then it will return 404 Not found otherwise it will return 200 OK response with employee data. Here, EmployeeViewModel is a POCO class with some properties. IHttpActionResult is an ActionResult for a request. We have other type of ActionResults like void, HttpResponseMessage, and other custom types etc. We will cover these types in some other article. The HTTPGet attribute decorator clearly saying that it will not allow any other HTTP verbs for the above method except GET method.

The GET method is called from client with some ajax call with a sample URL like below,

  • Uri format: http://serverUrl:serverPort/api/controllerName
  • Sample Url: http://localhost:12003/api/employee

The GET method can be useful in real time with the following important considerations.

  • We should not have same HTTP methods with the same number of parameters with the same type.
  • We can request the URL multiple times with no side effect. i.e Clicking on a hyperlink which redirects to another page has no side effect. This gives a chance to the browser to catch the response for faster retrieval.
  • The method GET is not secure. So, it is not suitable for transferring confidential data. You can just pass some configuration data or session id. The method is useful for retrieving content from a server.
  • The data that needs to be sent to the server is not large and can be a maximum length of  URL supported by all browsers.

HTTP POST

A post request is used to send complex objects/entities/uploading file etc to the server. In POST method data is sent as part of message body instead of sending as part of URL string to the server.

Example

  1. [HttpPost]  
  2. public IHttpActionResult AddNewEmployee(EmployeeViewModel employee)  
  3. {  
  4.     using (var context = new EmployeeDBEntities())  
  5.     {  
  6.         context.Students.Add(new Employee()  
  7.         {  
  8.             EmpID = employee.EmpID,  
  9.             EmployeeName = employee.EmployeeName,  
  10.             Designation = employee.Designation  
  11.         });  
  12.   
  13.         context.SaveChanges();  
  14.     }  
  15.   
  16.     return Ok();  
  17. }  

The above action method includes a parameter of the EmployeeViewModel type which contains all the information about a new employee. You can send HTTP POST request using Fiddler as shown below.

HTTP POST

The POST method can be useful in real time with the following important considerations.

  • Use POST while sending large data which can not be fit into URL.
  • POST method is secure because data is not visible in URL string. All sensitive data sent to the server must go through POST request and HTTPS (HTTP with SSL).
  • Use POST method while passing sensitive/confidential information to the server like user_id, password, account details etc.
  • Use POST method when altering the state of an application like payment processing, adding new entities etc.

HTTP PUT

HTTP PUT request is very much similar to POST request. If the resource/entity is already present in that specified URI, it will update that URL, if not present then it will create new one.

Example

  1. [HttpPut]  
  2. public IHttpActionResult UpdateEmployeeData(EmployeeViewModel employee)  
  3. {  
  4.     using (var context = new EmployeeDBEntities())  
  5.     {  
  6.         var employee_to_update = context.Employees.Where(e => e.EmpId ==  employee.Id).FirstOrDefault<Employee>();  
  7.   
  8.         if (employee_to_update != null)  
  9.         {  
  10.             employee_to_update.EmployeeName = employee.EmployeeName;  
  11.             employee_to_update.Designation = employee.Designation;  
  12.   
  13.             context.SaveChanges();  
  14.         }  
  15.         else  
  16.         {  
  17.             return NotFound();  
  18.         }  
  19.     }  
  20.   
  21.     return Ok();  

The above PUT request includes EmployeeViewModel object into JSON format in that request body. The action will create new employee entity and then changes the state to be modified. You can send HTTP PUT request using Fiddler as shown below.

HTTP PUT

HTTP DELETE

The HTTP DELETE request is useful for deleting an existing record from a data source. Which means the DELETE method is used to request the server to delete a file/record at a location specified by the URL.

Example

  1. [HttpDelete]  
  2. public IHttpActionResult Delete(int id)  
  3. {  
  4.     if (id <= 0)  
  5.         return BadRequest("Not a valid employee id");  
  6.   
  7.     using (var context = new EmployeeDBEntities())  
  8.     {  
  9.         var employee = context.Employees  
  10.             .Where(e => e.EmpID == id)  
  11.             .FirstOrDefault();  
  12.   
  13.        context.Entry(employee).State =    
  14.                      System.Data.Entity.EntityState.Deleted;  
  15.        context.SaveChanges();  
  16.     }  
  17.   
  18.     return Ok();  

The above request fetches an existing employee from the database with specified id and then marks its status as deleted. This will delete a particular record from database.

HTTP DELETE request using Fiddler as shown below

HTTP DELETE

It is not recommended to configure a web server for delete operation. Instead, it's better to do that operation with a HTTP POST operation with such functionality.

Note

Except above HTTP methods, the following verbs are rarely used in real-time.

HTTP TRACE

The TRACE request is used to troubleshoot request and response pipeline. Which means, for example, if the server is not responding to a particular request and taking a huge amount of time then HTTP TRACE request can be used to retrieve the complete request that the server received from the client back to the client itself.

This kind of implementation is mostly disabled in all web servers because it's very much equal to viewing web server log of that request.

HTTP HEAD

The HEAD request is very much similar to GET request. This is useful to get the complete details of the resource available on a particular URL without receiving complete data. Which means these requests useful only to retrieve attributes of the data without the complete data.

HTTP CONNECT

The CONNECT method is used to establish a network connect to a web server over HTTP.

Example:

Request

CONNECT localhost:12003 HTTP/1.1

User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)

Response

HTTP/1.1 200 Connection established

Date: Wed, 5 Jul 2017 12:30:53 GMT

HTTP OPTIONS

The OPTIONS method is used to find out the HTTP methods and other options supported by the server.

Up Next
    Ebook Download
    View all
    Learn
    View all