This article will help you to learn and understand how to Implementing CRUD Operations using WEB API. If you have not gone through my previous article I would like to suggest you please go through Creating your first WEB API Project, you will get a better understanding of “how to create and set up a web API project“. Just to make it simple and easy to understand we are going to use the basic concept of ADO.Net in order to perform CRUD operations. There are various ways you can write your code. No worry! we will learn how to perform CRUD operations by using different ways of Entity Framework in the later article. Now, let’s focus on basic first.
CRUD Stands for Create Read Update and Delete. The operations in this article will perform CRUD operation on the SQL server database. You can download the script and source code. The link is given at the end of the article. To perform this task, We are going to use a model which reflect the concept of repository pattern. In Model, we’ll have a class having all the table entities, One Interface defining CRUD operations and One class which will implement that Interface. One Controller where will have all actions Like GET, PUT, POST, DELETE.
Clients can access those operations in RESTful manner that is resource based. ASP.NET Web API framework will return a response in XML format by default. We can change it as per our need like JSON. No worry! we are going to learn all these things in this article.
Creating WEB API Application :
- Open Visual Studio 2013/15/17 either it is Community version, professional version or enterprise version.
- Click on File Menu
- Click on New and then Click on Project menu.
- This will open a new window – New project, where you can select the project type.
- Expand Installed, Expand Language and select web.
- Select .Net framework on which you are going to build your WEB API.
- Select Template. Here I’ve selected ASP.NET Web Application(.Net Framework)
- Enter Project Name. Here I’ve entered WEBAPI_CRUDOperations
- Click on OK button.
Create Model Classes :
[su_box title=”Why we need to create Model ? ” box_color=”#faf62b” title_color=”#151111″]Model is a class that maps to the data relation (table) and potentially bridge tables. The model represents the data and does nothing else. In short, this is where you should keep your data model and logic’s to get and set data.[/su_box]
Create a new folder with name Models under root directory If it is not available in your project. Now create a new class “Employee“. You can name it as per your need.
To Create a new class, follow given steps.
- Right click on Models
- Click on Add
- Click on Class and create a class name Employee
- And write below code. You can change it as per your table structure.
Create an Interface with the name “IEmployeeRepository“. You can name it as per your need.
Create a class with the name “EmployeeRepository” which will implement “IEmployeeRepository“. You can name it as per your need.
Write below code inside the EmployeeRepository class to access the database. GetData function will return Datatable (Represent One Table off in Memory Data) whenever you request a query in order to read the table.
Ok Fine! Now you have created models, classes with all entities mapped to table columns, defined Interfaces. Now you have to write code in order to implementation of CRUD operations.
Lets see below code to understand how to implement functions defined in “IEmployeeRepository”
Create a Controller :
Now you have to create Controller where you can write action method in order to expose your data to the client can consume it. To create a controller follow given steps.
- Expand Installed
- Click on Controller
- Select Controller template. Here we are using Web API 2 Controller – Empty
- Click on OK button.
[su_note]The Controller class plays an important role because requests coming from the client hits the controller first. Then the controller decides which model to use to serve the incoming request. [/su_note]
Add below code in “EmployeeController” to access required actions in order to perform CRUD operations.
[su_box title=”Why we use Request.CreateResponse and Request.CreateErrorResponse ?” box_color=”#faf62b” title_color=”#151111″]CreateResponse – Creates an HttpResponseMessage wired up to the associated HttpRequestMessage.
CreateErrorResponse – Because it creates an HttpResponseMessage that represents an error. [/su_box]
The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD(Create Read Update Delete) operations as follows:
- GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.
- PUT updates a resource at a specified URI. PUT can also be used to create a new resource at a specified URI, if the server allows clients to specify new URIs.
- POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.
- DELETE deletes a resource at a specified URI.
|Action||HTTP method||Relative URI|
|Get a list of all Employee||GET||api/Employee/GET|
|Get an Employee by ID||GET||api/Employee/GET/ID|
|Create a new Employee||POST||api/Employee/PostEmployee|
|Update an Employee||PUT||api/Employee/PutEmployee|
|Delete an Employee||DELETE||api/Employee/DeleteEmployee|
Configuring Routing Table
Whenever HTTP(Hyper Text Transfer Protocol) requests received by the Web API framework, it always uses the routing table to determine which action have to be invoked.
Web API framework first selects controller by IHttpControllerSelector.SelectController method and then selects action method by IHttpActionSelector.SelectAction depending on matching the value in request URI and configured route table.
You can configure a route table in WebApiConfig.cs file. So open this file from App_Start folder add below code.
After writing above code, make sure you have also mentioned below code in Global.asax.cs
Done! Now you have learned how to write code for basic crud operation using WEB API in Asp.Net. As we already discussed in my previous article based on WEB API, we can use tools to check WEB API is working correctly or not. Fiddler and Postman are two great and free available tools with the help you can easily check services.
[su_box title=”URL to check WEB API CRUD Actions” box_color=”#faf62b” title_color=”#151111″]
Now you can execute below RESTful Read operation using browser. The first URL will return all Customers and the second URL will read single customer depending on customerID provided. You might have to change the port number.
To get return response in JSON format you have to write one addition line in Register function of WebApiConfig class
Otherwise, whenever you execute GET request, ASP.NET Web API framework will return a response in XML format by default.
You can download complete source code from here
[su_button url=”https://github.com/code-adda/WEBAPI_CRUDOperations” target=”blank” style=”3d” background=”#7a1d18″ size=”5″ radius=”round”]Download Source Code [/su_button]
You can also use authentication and authorization in your WEB API CRUD application to make it more secure in order to expose your WEB API resources to the client side. You can read our article based on WEB API Authentication.
Coming days, you can see a bunch of new articles.
- How to Perform CRUD operation by using Fiddler. Here we’ve learned how to create WEB API but we didn’t learn how to test CRUD operation as a client.
- We will learn how to perform CRUD operations using WEB API and Entity Framework Code First approach.
Till then stay tuned. Share our article among needy friends. Happy Coding !!