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.
- public class EmployeeController : ApiController
- {
-
- [HttpGet]
- public IHttpActionResult GetAllEmployees(){
- using (var context = new EmployeeDBEntities())
- {
- employees = context.Employees
- .Select(e => new EmployeeViewModel()
- {
- Id = e.EmpID,
- FirstName = e.EmployeeName,
- Designation = e.Designation
- }).ToList<EmployeeViewModel>();
- }
-
- if (employees.Count == 0)
- {
- return NotFound();
- }
-
- return Ok(employees);
- }
- }
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
- [HttpPost]
- public IHttpActionResult AddNewEmployee(EmployeeViewModel employee)
- {
- using (var context = new EmployeeDBEntities())
- {
- context.Students.Add(new Employee()
- {
- EmpID = employee.EmpID,
- EmployeeName = employee.EmployeeName,
- Designation = employee.Designation
- });
-
- context.SaveChanges();
- }
-
- return Ok();
- }
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.
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
- [HttpPut]
- public IHttpActionResult UpdateEmployeeData(EmployeeViewModel employee)
- {
- using (var context = new EmployeeDBEntities())
- {
- var employee_to_update = context.Employees.Where(e => e.EmpId == employee.Id).FirstOrDefault<Employee>();
-
- if (employee_to_update != null)
- {
- employee_to_update.EmployeeName = employee.EmployeeName;
- employee_to_update.Designation = employee.Designation;
-
- context.SaveChanges();
- }
- else
- {
- return NotFound();
- }
- }
-
- 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 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
- [HttpDelete]
- public IHttpActionResult Delete(int id)
- {
- if (id <= 0)
- return BadRequest("Not a valid employee id");
-
- using (var context = new EmployeeDBEntities())
- {
- var employee = context.Employees
- .Where(e => e.EmpID == id)
- .FirstOrDefault();
-
- context.Entry(employee).State =
- System.Data.Entity.EntityState.Deleted;
- context.SaveChanges();
- }
-
- 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
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.