Friday 5 August 2016

Restful API | Enabling CRUD Operations


This is continuation of previous article, here we will enable POST, PUT and DELETE operations for the webapi. Lets first add support for POST operation, in service layer add new interface method AddProduct and the implementation is shown below. Using EF, we add new entry to the model and render the data requested back to client.
In webapi, lets add POST method which takes Product Model as input parameter, this invokes service layer AddProduct method.
Lets run and test the functionality. In Postman, lets do a post request with a product data and the information is saved in DB.
I made changes in product table to have primary key as ProductID and enabled auto increment for this column. In order update the model, open edmx file right choose update model from database option and in refresh table choose the update and click finish as shown below.
Let try to place once more POST request with invalid ProductID, exception is thrown and http 400 Bad Request status is got back with the exception details.
Here is the corresponding changes in interface and implementation to add PUT and DELETE operation.

Let add functionalities to support PUT and DELETE operation in WebApi.
Run and test the project using Postman for PUT and DELETE feature. 

PUT Operation, updated the price and quantity information but this updated the completed record, say all the columns. Best way to do update using EF is to get the data from DB and use it as part of update.
DELETE operation, removed the product 3 from DB.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.