The Most Perfect CRUD Operations!

As you know, HTTP is RESTful Protocol with the HTTP Verbs meant for CRUD mapping initially.

But I am seeing may Wrong Doings in Implementation like:

  • Wrong HTTP Method for Operation
  • Wrong Naming Conventions

Perfect Mapping

Here I would like to Map in the Perfect Way recommended by Microsoft.

  • CREATE operation can be mapped to POST
  • READ operation can be mapped to GET
  • UPDATE operation can be mapped to PUT
  • DELETE operation can be mapped to DELETE

Note

CREATE is essentially mapped to POST and Visual Studio Code Generation also recommends same.

Example

Here I am creating a CRUD Controller with the above Method Representations.

    [Route(“api/[controller]”)]
public class EmployeeController : Controller
{
private static IDictionary<int, string> _list = new Dictionary<int, string>();

public EmployeeController()
{
if (_list.Count == 0)
{
_list.Add(1, “Amar”);
_list.Add(2, “Akbar”);
_list.Add(3, “Antony”);
}
}

// GET: api/<controller>
         [HttpGet]
public IEnumerable<string> Get()
{
return _list.Values;
}

// GET api/<controller>/5
         [HttpGet(“{id}”)]
public string Get(int id)
{
string result = string.Empty;

_list.TryGetValue(id, out result);

return result;
}

// POST api/<controller>
         [HttpPost]
public void Post([FromBody]string value)
{
_list.Add(_list.Keys.Max() + 1, value);
}

// PUT api/<controller>/5
         [HttpPut(“{id}”)]
public void Put(int id, [FromBody]string value)
{
_list[id] = value;
}

// DELETE api/<controller>/5
         [HttpDelete(“{id}”)]
public void Delete(int id)
{
_list.Remove(id);
}
}

Execution

On execution we can play with Postman against the same Controller Name and changing the HTTP Verbs.

image

Following are the actual UI screenshots.

List

image

Insert

image

Update

image

Delete

image

Summary

The reason I call his the Most Perfect CRUD operations is because the same controller name is used for all the 4 operations.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s