The term REST has been coming up a fair amount over the last while so I thought I would look deeper into what this means and how I would use it. I am primarily develop web related applications so I was interested in how this would affect the way that I design / architect the solutions I am involved in.
What is it
Rest (Representational state transfer, thanks wikipedia) is an architectural concept in which defines rules for the way that applications communicate. For the most part when I was researching this, most of the definitions tended to focus mainly on REST vs. SOAP, but it could be applied to any interaction between applications. To be defined as Restful the application must be designed according to the following principles:
- All components being accessed in the system are all accessed in a unique way. To break this down we need to understand that the way that we access the component we would need to know what we are accessing or the name of the component as well as a identifier for that component. This means that if I was to get this article from the blog then I would use a URL that clear defines what it is I am looking for: www.blog.com/article/1.
- The API should respond to all calls with an appropriate response code and / or a JSON object:
- 200 OK
- 201 Created
- 204 No Content
- 400 Bad Request
- 401 Unautherized
- 500 Internal Error
- Use commonly know actions to allow the client to communicate with the system. In this case it should be common HTTP actions: GET, POST, PUT etc
Example
public class RestController : ApiController { // GET api/values public IEnumerable<JsonUser> Get() { return new IList<JsonUser>(); } // GET api/values/5 public JsonUser Get(int id) { return new JsonUser(); } // POST api/values public void Post(JsonUser user) { //Add saving logic here } // PUT api/put public void Put(JsonUser user) { //Add saving logic here } // DELETE api/delete/5 public void Delete(int id) { //Add Deleting logic here } }