ASP.NET Web API With Fiddler And Postman

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.

  1. GET- It is used to fetch the data.
  2. PUT- It is used to update the data.
  3. POST- It is used to create the data.
  4. 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.

  1. CREATE TABLE [dbo].[Product] (  
  2.     [Id]       INT           IDENTITY (1, 1) NOT NULL,  
  3.     [Name]     VARCHAR (100) NOT NULL,  
  4.     [Price]    INT           NOT NULL,  
  5.     [Category] VARCHAR (100) NOT NULL,  
  6.     PRIMARY KEY CLUSTERED ([Id] ASC)  
  7. )  
  8.    
  9. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (1, N'Mobile', 500, N'Electronics')  
  10. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (2, N'Tablet', 700, N'Electronics')  
  11. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (3, N'Mouse', 200, N'Electronics')  
  12. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (4, N'Keyboard', 340, N'Electronics')  
  13. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (5, N'Speakers', 5000, N'Electronics')  
  14. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (6, N'T-Shirts', 100, N'Wearables')  
  15. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (7, N'Pants', 120, N'Wearables')  
  16. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (8, N'Jeans', 540, N'Wearables')  
  17. INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (9, N'Chips', 50, N'Eatables')  
  18. 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. 

  1. public ProductEntities Entities = new ProductEntities();  
  2.    
  3.         public HttpResponseMessage Get()  
  4.         {  
  5.             try  
  6.             {  
  7.                 return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.ToList());  
  8.             }  
  9.             catch (Exception)  
  10.             {  
  11.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");  
  12.             }  
  13.         }  
  14.    
  15.         public HttpResponseMessage Get(int id)  
  16.         {  
  17.             try  
  18.             {  
  19.                 return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.SingleOrDefault(p => p.Id == id));  
  20.             }  
  21.             catch (Exception)  
  22.             {  
  23.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");  
  24.             }  
  25.         }  
  26.    
  27.         public HttpResponseMessage Post([FromBody] Product product)  
  28.         {  
  29.             try  
  30.             {  
  31.                 Entities.Products.Add(product);  
  32.                 Entities.SaveChanges();  
  33.                 var response = Request.CreateResponse(HttpStatusCode.Created, product);  
  34.                 response.Headers.Location = Request.RequestUri;  
  35.    
  36.                 return response;  
  37.             }  
  38.             catch (Exception)  
  39.             {  
  40.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data not inserted");  
  41.             }  
  42.         }  
  43.    
  44.         public HttpResponseMessage Delete(int id)  
  45.         {  
  46.             try  
  47.             {  
  48.                 var product = Entities.Products.SingleOrDefault(p => p.Id == id);  
  49.                 if (product == null)  
  50.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found to delete");  
  51.                 Entities.Products.Remove(product);  
  52.                 Entities.SaveChanges();  
  53.    
  54.                 return Request.CreateResponse(HttpStatusCode.OK, "Product Deleted Successfully");  
  55.             }  
  56.             catch (Exception)  
  57.             {  
  58.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not deleted");  
  59.             }  
  60.         }  
  61.    
  62.         public HttpResponseMessage Put(int id, [FromBody] Product product)  
  63.         {  
  64.             try  
  65.             {  
  66.                 var entity = Entities.Products.SingleOrDefault(p => p.Id == id);  
  67.                 if (entity == null)  
  68.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found ");  
  69.    
  70.                 entity.Category = product.Category;  
  71.                 entity.Name = product.Name;  
  72.                 entity.Price = product.Price;  
  73.                 Entities.SaveChanges();  
  74.    
  75.                 return Request.CreateResponse(HttpStatusCode.OK, "Product Updated Successfully");  
  76.             }  
  77.             catch (Exception ex)  
  78.             {  
  79.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  80.             }  
  81.         }  
Step 10

Go to
App_Start folder of the root directory and open WebApiConfig.cs file. Add the lines of code given below.
  1. config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));  
  2. config.Formatters.Remove(config.Formatters.XmlFormatter);  

The two lines given above make APIs which are only JSON supported. Hence, by default, now our API will support only JSON Media type format.

Now, our API is ready. Just add the connection string given below to the API’s web.config file.

  1. <add name="ProductEntities"  
  2. connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;  
  3. provider=System.Data.SqlClient;provider connection string="  
  4. data source=(local);initial catalog=DemoDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""  
  5. providerName="System.Data.EntityClient" />  

Press Ctrl + F5 and navigate to http://localhost:26317/api/products. You will see the details of the product table in JSON format, as shown below.

Now, as per the agenda of this article, we will install Fiddler tool and Postman tool to test API functionality.

Using Fiddler to test Web Api

Step 1

Download Fiddler from the URL given below in the screenshot.

Install the downloaded EXE file and run it.

Step 2

First, we will check GET functionality. Thus, follow the steps shown in the screenshot given below and you will get the result in JSON format.

fiddlerdel1

Step 2

Now, we will test POST (Insert) functionality.

Now, the data is inserted on 12th row.

Step 3

Now, we will update the data on 12th ID, using PUT functionality.

Now, the data is updated successfully.

Step 4

Now, we will delete the 12th record.

Using Fiddler to just test if the Web API functionality looks complicated, so instead of using Fiddler, we can use Postman (Google Chrome Extension).

Using Postman to test Web Api

Step 1

Install Postman app in Google Chrome Browser, as shown below.

Step 2

Run Postman app from the apps option in Google Chrome Browser. Thus, now test GET functionality.

Step 3

Test POST functionality.

The record is inserted at 13th row.

Step 4

Test PUT functionality.

Hence, the data is updated in the database.

Step 5

Finally, test Delete functionality.

Conclusion

Personally, I like using Postman to test Web API’s and WCF Services. We can also use Fiddler, but if API is too complex, I recommend using Fiddler, as it gives more flexibility to test the Services.

I hope you liked the above tutorial. If so, comment with your compliments and queries. I will try to reply asap. 


Similar Articles