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.
Following are the actual UI screenshots.
List
Insert
Update
Delete
Design Guidelines
- Do not expose Database Structure through APIs.
- Avoid Chatty API Requests which will degrade the performance
- Asynchronous operations gives better Client experience. Return 202 status & Provide Monitor URL for observing the status.
- Use Pagination to optimize usage of resources – especially in PaaS style programming where Cost depends on the usage.
- Limit the return Field parameters to optimize traffic
- Use HATEOS inside responses which are Links to the subsequent operations which helps Navigating around all the operations associated with the resources
- Implement Versioning so new APIs can be supported without affecting the existing clients
References
Summary
The reason I call his the Most Perfect CRUD operations is because the same controller name is used for all the 4 operations.