What is REST or RESTful service?
REST stands for Representational State Transfer. It is an architectural concept for building inter-operable light weight web services which helps to access and manipulate the web resources identified though URI (Uniform Resource Identifier). It was introduced by Roy Fielding and was later adopted heavily by the industry. Like WWW (World Wide Web, REST identifies all resources on server through a unique URI. For example: http://yoursite.com/employee/1 to access the employee information with id 1. The REST web service accepts a requests for a resource and returns response in almost every data interchange formats like XML, JSON, HTML, etc.
All these days, there were other web service technologies that works using SOAP and HTTP protocols. These are primary web service technologies that are typically used in distributed systems. Though these services works on HTTP and fulfills all the service needs, these web service framework heavily exploited HTTP protocol. For example, to access a employee information, we need to make http call to say http://yoursite.com/customers.asmx with a SOAP envelop that looks like below.
<soap:Body xmlns:em="http://www.yoursite.org/employee">
<em:GetEmployee>
<em:EmployeeId>1</em:EmployeeId>
</em:GetEmployee>
</soap:Body>
The service will respond with a SOAP message similar to below.
<soap:Body xmlns:em="http://www.yoursite.org/employee">
<em:GetEmployeeResponse>
<em:EmployeeId>1</emmEmployeeId>
<em:Name>Tom</em:Name>
<em:Department>IT</em:Department>
<em:Gender>Male</em:Gender>
</em:GetEmployeeResponse>
</soap:Body>
All works fine, but when you really see what is happening underneath, the actual request to get the employee detail is made through a POST request where the service would have responded with HTTP 200 success status code by returning the employee detail information in a SOAP envelop. The service would still respond with HTTP 200 even when the requested employee Id is not found on the server but indicates the caller only through some custom error message or fault message using a SOAP envelop.
Using HTTP in correct sense, to access or get a resource from server we should always use GET method and the server should respond to the GET request with a HTTP 200 response only when it is able to cater requested resource. The response should be 404 not found when the requested resource is not found.
This is where REST comes into picture which uses HTTP protocol as defined in its specification with correct usage of HTTP verbs like GET,POST,PUT,DELETE and with appropriate HTTP status codes like 200( only if it is successful), 201 (if new resource created by using POST), 404(when requested resource not found), etc. So, the above example in REST API can be made similar to below.
Request
GET /employee/2 HTTP/1.1 http://www.yoursite.org
Accept: application/vnd.employee+json
Response
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"data": [
{
"id": "2",
"Name": "John",
"Department": "Sales"
}
],
"links": {
"self": "http://yoursite.com/employee/2",
"prev": "http://yoursite.com/employee/2",
"next": "http://yoursite.com/employee/2",
"last": "http://yoursite.com/employee/2001"
}
}
Now, if you see the above request and response, the REST services are very light weight (no bulk soap envelop xml) and usage http verbs, status codes are appropriate (REST would return 404 if not found here). The other response item “links” will help the client to identify the current resource (if it is created newly using POST) and discover the other related resources. This particular concept is called hypermedia which helps the client to navigate to the next resource. This means a REST client, thereby by accessing a resource, the client can continuously access the next resource using the links provided in the REST response. This constraint the REST architecture follows is typically called HATEOAS, Hypermedia As The Engine Of Application State. A good read on hypermedia is here for reference. A REST service also enables content negotiation with the client to respond in a format which the client understands and vice versa.
Thus, a REST service uses the capabilities of HTTP to provide a simple but powerful web services by using hypermedia to handle heterogeneous client-server communication efficiently. REST also helps clients and services to evolve separately as opposed to classic service technologies.
Creating RESTful Services in Asp.Net
We can create RESTful service in Asp.Net using Asp.Net Web API framework. The Asp.Net WebApi framework is built very similar to Asp.Net MVC framework. Like MVC framework, we have Controllers, Action, Routing, Action Filters, Model binding, Model validations, etc. Though it is built similar to ASP.Net MVC, WebApi is built as standalone framework, meaning the whole framework is shipped as separate Nuget packages that does not have any dependency on Asp.Net MVC framework. The WebApi project can be hosted in IIS or it can be self-hosted in a separate process.
WebApi is also referred as HTTP API and it is deliberately not called REST API for many reasons. As per Roy Fielding’s REST architecture, an API without hypermedia is not completely RESTful. Practically speaking, not every API we expose needs hypermedia. An interesting read about REST without HyperMedia is here. Though Asp.Net WebApi framework allows building REST API it does not force you to build every service you expose as REST API. It uses the REST architecture’s capability of using HTTP programming model to expose light weight web services to support multiple clients.
Next section, we will see how to create web API using Visual Studio 2015.
Creating WebApi project in Visual Studio 2015
-
Open Visual Studio 2015. Click New > Project
-
Select Web templates and ASP.Net Web Application.
-
Select Empty template and check Web API for “Add folders and core reference for”. Refer below image.
Click OK.
This will create a new empty WebApi project with all required Nuget packages, default routing setup required to create your first web API.
-
Add a Web API controller by right clicking Controllers folder and Add > Controller.. Select WebAPI 2.0 controller with read/write actions.
I have only added a simple Get() and Get(id) action methods to return hardcoded employee information for simplicity.
Employee API Controller
public class EmployeeController : ApiController
{
// GET api/<controller>
public IEnumerable<Employee> Get()
{
return new[] { new Employee { Id = 1, Name = "Tom", Gender = "Male" }, new Employee { Id = 2, Name = "John", Gender = "Male" } };
}
// GET api/<controller>/5
public Employee Get(int id)
{
return new Employee() { Id = 1, Name = "Tom", Gender = "Male" };
}
// POST api/<controller>
public void Post([FromBody]string value)
{
//post code
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
//put code
}
// DELETE api/<controller>/5
public void Delete(int id)
{
//delete code
}
}
Employee model
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
-
Press F5 to execute the application.
Visiting http://localhost:56323/api/employee will list all the employees.
Visiting http://localhost:56323/api/employee/1 will list employee information for employee id 1.
Note- replace the port # with your project’s port number.
Changes in .Net Core
In Asp.Net Core Web API framework, the MVC base Controller class and Web API’s ApiController base class which the controllers inherit are unified. This means WebApi and Asp.Net MVC controller in Asp.Net Core framework are same.