In the last post we implemented CRUD operations with Web API. According to HTTP method definitions, all the HTTP requests should return a HTTP response, which consists of
Response Message Body (optional)
So we can rewrite all these methods with HttpResponseMessage class,this class help to create HTTP response message including the status code and data. You can use Request property exposed by APIController to create HttpResponseMessage.
So you can re-write the Get method like this.
If you look at the response, you can see the response code is 200.
Here is the curl request to invoke the Get method.
And here is the response.
And to get a selected employee, you can send Get Request with Id. Here is the service implementation.
And here is curl request.
Response will be similar to the GET request without the Id. It will be 404 Not Found, if you send a request with a no existing Id, like 100. Here is the error response, which contains status code 404 Not Found and Error Message we provided while creating the error response.
For POST request, according to HTTP method definitions - “if a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header”. And here is the implementation, which will insert the entity and returns the response with Entity and location.
Here is the POST request.
Response from Web API.
You can see the status code 201 Created. Response also contains the location of the newly created resource and created entity. Similar to POST you can re-write PUT and DELETE requests also. For both PUT and DELETE requests, responses is similar.
Did you like this article? Share it with your friends