Agenda
- Creating the very basic Web API project in Visual Studio.
- Creating methods to perform CRUD (Create, Read, Update and Delete) operations with WebApi Controller using ADO.NET Entity Framework 6.1.3.
- Learning the way to make your Web API return the data in specific formats like JSON, XML etc.
- Downloading and installing Fiddler tool and testing the Web API with it.
- Downloading and installing Postman tool and testing the Web API with it.
ASP.NET Web API is a framework that allows us to build HTTP Services at the top of .NET Framework. It is so flexible that it can reach a broad range of clients, including the Browsers and portable devices. It’s main feature, which makes it unique, is that it is RESTful (Representational State Transfer) i.e. all that data is passed over HTTP and not on SOAP like that of WCF Services.
Unlike SOAP, a Web API works on pre-defined standards i.e. it has pre-defined verbs, known as HTTP verbs, which are required to work. These verbs are mentioned below.
- GET- It is used to fetch the data.
- PUT- It is used to update the data.
- POST- It is used to create the data.
- DELETE- It is used to delete the data.
Note
ASP.NET Web API works on MVC (Model-View-Controller) architectural pattern, so MVC is a prerequisite.
Creating a Web API Project in Visual Studio
Step 1
Run Visual Studio on your machine and click on New Project.
Step 2
The dialog box given below appears, click on Web under Visual C# tab –> ASP.NET Web Application –> Give the name of the project –> OK.

Step 3
Select Web API option and click OK.

Step 4
Create the database and insert some sample data, using the SQL script given below.
- CREATE TABLE [dbo].[Product] (
- [Id] INT IDENTITY (1, 1) NOT NULL,
- [Name] VARCHAR (100) NOT NULL,
- [Price] INT NOT NULL,
- [Category] VARCHAR (100) NOT NULL,
- PRIMARY KEY CLUSTERED ([Id] ASC)
- )
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (1, N'Mobile', 500, N'Electronics')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (2, N'Tablet', 700, N'Electronics')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (3, N'Mouse', 200, N'Electronics')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (4, N'Keyboard', 340, N'Electronics')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (5, N'Speakers', 5000, N'Electronics')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (6, N'T-Shirts', 100, N'Wearables')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (7, N'Pants', 120, N'Wearables')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (8, N'Jeans', 540, N'Wearables')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (9, N'Chips', 50, N'Eatables')
- INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (10, N'Coke', 30, N'Eatables')
The final table will be look, as shown below.

Now, we need to do all the CRUD operations on the above table and the data.
Step 5
Create a Class Library project, which connects to the database and provides us with the required classes and properties, using ADO.NET Entity framework.










Step 6
After clicking Finish button, you will see the below EDMX file, which shows the data-entity relationship, as defined in database.

Now, we are done with the connectivity to the database.
Step 7
Now, we need to add the reference of the above created project in our Web API project, so follow the steps given below.


Step 8
Now, we need to create a new ProductsController.cs file in the Controllers folder of Web API Project. This file will contain the methods that correspond to HTTP verbs, which we discussed in the very beginning of this tutorial.


Step 9
Add the code given below to ProductsController.cs.
- public ProductEntities Entities = new ProductEntities();
- public HttpResponseMessage Get()
- {
- try
- {
- return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.ToList());
- }
- catch (Exception)
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
- }
- }
- public HttpResponseMessage Get(int id)
- {
- try
- {
- return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.SingleOrDefault(p => p.Id == id));
- }
- catch (Exception)
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
- }
- }
- public HttpResponseMessage Post([FromBody] Product product)
- {
- try
- {
- Entities.Products.Add(product);
- Entities.SaveChanges();
- var response = Request.CreateResponse(HttpStatusCode.Created, product);
- response.Headers.Location = Request.RequestUri;
- return response;
- }
- catch (Exception)
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data not inserted");
- }
- }
- public HttpResponseMessage Delete(int id)
- {
- try
- {
- var product = Entities.Products.SingleOrDefault(p => p.Id == id);
- if (product == null)
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found to delete");
- Entities.Products.Remove(product);
- Entities.SaveChanges();
- return Request.CreateResponse(HttpStatusCode.OK, "Product Deleted Successfully");
- }
- catch (Exception)
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not deleted");
- }
- }
- public HttpResponseMessage Put(int id, [FromBody] Product product)
- {
- try
- {
- var entity = Entities.Products.SingleOrDefault(p => p.Id == id);
- if (entity == null)
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found ");
- entity.Category = product.Category;
- entity.Name = product.Name;
- entity.Price = product.Price;
- Entities.SaveChanges();
- return Request.CreateResponse(HttpStatusCode.OK, "Product Updated Successfully");
- }
- catch (Exception ex)
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
























Krishna NigalyePosted Dec 2, 2019, 6:25 AM
Great Article! Very helpful.
SAI ALURIPosted Sep 18, 2019, 2:14 AM
Good Article for Learning on Api's
Manikandan SaminathanPosted Feb 2, 2019, 12:14 PM
Very helpful to a beginner like me
Shrikant JagtapPosted Dec 18, 2018, 2:42 AM
Need Help on IOT
Shrikant JagtapPosted Dec 18, 2018, 2:42 AM
Need Help on IOT
Alok DubeyPosted Sep 4, 2018, 8:26 AM
Fantastic ankit ,,great
susilkumar beheraPosted Jan 2, 2018, 1:26 AM
Can we inserted multiple data at a time using postman
Kunal PanchalPosted Jun 27, 2017, 6:06 AM
Nice Article in Simple Ways
Muhammad Aqib ShehzadPosted Jan 30, 2017, 1:15 AM
Very nice article with well prepared stuff step wise Thanks for sharing.. i have a few questions 1) what is mean by [FromBody] in webapi method params. 2) HttpStatusCode.NotFound, "No Data found") this cause the error in your log and also in console of type 404 is this is the good approach or we can use it better way to check the no record found in database.
Rathrola Prem KumarPosted Jan 27, 2017, 10:43 AM
Thanks for sharing, perfect explanation :)
Raghavendra SPosted Jan 25, 2017, 8:55 AM
Good article. Can you add examples where transaction scope is also used?
Bikesh SrivastavaPosted Jan 25, 2017, 8:42 AM
Very nice article ,well explained.
Ankit BansalPosted Jan 24, 2017, 10:29 AM
Thanks team for considering my article as featured..
Ravi PatelPosted Jan 24, 2017, 5:44 AM
Thank you so much for nice article
Nilesh ShahPosted Jan 23, 2017, 4:04 PM
Indeed very informative, thanks for your efforts in preparing the screen shots!