In this article we are going to see how we test our API with the help of a package called WebApiTestClient. As you all know, if you create a sample API project you will get a folder HelpPage in Areas. This is for adding the XML description to each controller and actions we use in our API. If you document it well, any one can understand your API, so that you don’t need to explain what your API will do and what would be the output. If you are new to HelpPage implementation in API, please see here: API help page controller action description in Web API. Here we will to create a Web API with the help page descriptions in Visual Studio 2015. Once the project is ready we will install the WebApiTestClient package to the solution.
Please be noted that this package is not officially released by Microsoft. This is a prototype created by Yao – MSFT
Download the source code
You can always download the source code here: API Test Client
Background
For the past few months, I had been working with API projects. Recently I was asked to create an application to test the API I created so that the testing team can test the API easily. Yes I agree that we have tools like Fiddler and Post Man for the same. Still we thought to create our own. As I started my development, I came to know about the package WebApiTestClient which does what we wanted. Finally we decided to stop developing the application and used this wonderful package. Here I am going to show you how can we use this.
Prerequisites
Things we are going to do
The following are the tasks we are going to do.
Setting up database
Here I am going to create a database which I created for my demo purposes, you can always create this database by running the queries mentioned here.
Create database
USE [master]
GO
/****** Object:
Database
[TrialsDB] Script
Date
: 5/12/2016 10:56:41 AM ******/
CREATE
DATABASE
[TrialsDB]
CONTAINMENT = NONE
ON
PRIMARY
(
NAME
= N
'TrialsDB'
, FILENAME = N
'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf'
,
SIZE
= 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG
'TrialsDB_log'
'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf'
= 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
ALTER
SET
COMPATIBILITY_LEVEL = 110
IF (1 = FULLTEXTSERVICEPROPERTY(
'IsFullTextInstalled'
))
begin
EXEC
[TrialsDB].[dbo].[sp_fulltext_database] @
action
=
'enable'
end
ANSI_NULL_DEFAULT
OFF
ANSI_NULLS
ANSI_PADDING
ANSI_WARNINGS
ARITHABORT
AUTO_CLOSE
AUTO_CREATE_STATISTICS
AUTO_SHRINK
AUTO_UPDATE_STATISTICS
CURSOR_CLOSE_ON_COMMIT
CURSOR_DEFAULT
GLOBAL
CONCAT_NULL_YIELDS_NULL
NUMERIC_ROUNDABORT
QUOTED_IDENTIFIER
RECURSIVE_TRIGGERS
DISABLE_BROKER
AUTO_UPDATE_STATISTICS_ASYNC
DATE_CORRELATION_OPTIMIZATION
TRUSTWORTHY
ALLOW_SNAPSHOT_ISOLATION
PARAMETERIZATION SIMPLE
READ_COMMITTED_SNAPSHOT
HONOR_BROKER_PRIORITY
RECOVERY
FULL
MULTI_USER
PAGE_VERIFY CHECKSUM
DB_CHAINING
FILESTREAM( NON_TRANSACTED_ACCESS =
)
TARGET_RECOVERY_TIME = 0 SECONDS
READ_WRITE
Create table with data
USE [TrialsDB]
Table
[dbo].[Product] Script
: 5/12/2016 10:54:48 AM ******/
TABLE
[dbo].[Product](
[ProductID] [
int
]
NOT
NULL
[
Name
] [nvarchar](
max
[ProductNumber] [nvarchar](25)
[MakeFlag] [
bit
[FinishedGoodsFlag] [
[Color] [nvarchar](15)
[SafetyStockLevel] [
smallint
[ReorderPoint] [
[StandardCost] [money]
[ListPrice] [money]
Size
] [nvarchar](5)
[SizeUnitMeasureCode] [
nchar
](3)
[WeightUnitMeasureCode] [
[Weight] [
decimal
](8, 2)
[DaysToManufacture] [
[ProductLine] [
](2)
[Class] [
[Style] [
[ProductSubcategoryID] [
[ProductModelID] [
[SellStartDate] [datetime]
[SellEndDate] [datetime]
[DiscontinuedDate] [datetime]
[rowguid] [uniqueidentifier] ROWGUIDCOL
[ModifiedDate] [datetime]
] TEXTIMAGE_ON [
INSERT
[dbo].[Product] ([ProductID], [
], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [
], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate])
VALUES
(1, N
'Adjustable Race'
, N
'AR-5381'
, 0, 0,
, 1000, 750, 0.0000, 0.0000,
, 0,
CAST
(0x0000921E00000000
AS
DateTime),
'694215b7-08f7-4c0d-acb1-d734ba44c0c8'
(0x00009A5C00A53CF8
DateTime))
(2, N
'Bearing Ball'
'BA-8327'
'58ae3c20-4f3a-4749-a7d4-d568806cc537'
(3, N
'BB Ball Bearing'
'BE-2349'
, 1, 0,
, 800, 600, 0.0000, 0.0000,
, 1,
'9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e'
(4, N
'Headset Ball Bearings'
'BE-2908'
'ecfed6cb-51ff-49b5-b06c-7d8ac834db8b'
(316, N
'Blade'
'BL-2036'
'e73e9750-603b-4131-89f5-3dd15ed5ff80'
(317, N
'LL Crankarm'
'CA-5965'
, 0, 0, N
'Black'
, 500, 375, 0.0000, 0.0000,
'L '
'3c9d10b7-a6b2-4774-9963-c19dcee72fea'
(318, N
'ML Crankarm'
'CA-6738'
'M '
'eabb9a92-fa07-4eab-8955-f0517b4a4ca7'
Our database is ready, now create a Web API application in visual studio and then entity with the above mentioned database.
Creating Entity
If you don’t know how to create an entity in your solution, please read that here. I have mentioned the steps to be followed in that article. Once you have created the entity, you are good to go and create a API controller with the entity created. If you do so, The CRUD actions will be created automatically for you. You may need to edit those actions according to your needs.
Web API 2 Controller with actions, using Entity Framework
Select the Model Class, DBContext then name your controller and click OK. I hope a controller with the CRUD actions. Now we can modify that as follows.
using
System;
System.Collections.Generic;
System.Data;
System.Data.Entity;
System.Data.Entity.Infrastructure;
System.Linq;
System.Net;
System.Net.Http;
System.Web.Http;
System.Web.Http.Description;
ControllerActionDescriptions.Models;
namespace
ControllerActionDescriptions.Controllers
{
public
class
ProductsController : ApiController
private
TrialsDBEntities db =
new
TrialsDBEntities();
#region GetProducts
/// <summary>
/// Get all the products available
/// GET: api/Products
/// </summary>
IQueryable<Product> GetProducts()
return
db.Products;
}
#endregion
#region GetProductWithParameter
/// Get a single product by id
/// GET: api/Products/5
/// <param name="id"></param>
[ResponseType(
typeof
(Product))]
IHttpActionResult GetProduct(
id)
Product product = db.Products.Find(id);
if
(product ==
null
NotFound();
Ok(product);
// PUT: api/Products/5
void
))]
IHttpActionResult PutProduct(
id, Product product)
(!ModelState.IsValid)
BadRequest(ModelState);
(id != product.ProductID)
BadRequest();
db.Entry(product).State = EntityState.Modified;
try
db.SaveChanges();
catch
(DbUpdateConcurrencyException)
(!ProductExists(id))
else
throw
;
StatusCode(HttpStatusCode.NoContent);
// POST: api/Products
IHttpActionResult PostProduct(Product product)
db.Products.Add(product);
(DbUpdateException)
(ProductExists(product.ProductID))
Conflict();
CreatedAtRoute(
"DefaultApi"
{ id = product.ProductID }, product);
// DELETE: api/Products/5
IHttpActionResult DeleteProduct(
db.Products.Remove(product);
protected
override
Dispose(
bool
disposing)
(disposing)
db.Dispose();
base
.Dispose(disposing);
ProductExists(
db.Products.Count(e => e.ProductID == id) > 0;
Installing WebApiTestClient
To install the package, please go to your Package Manage Console from NuGet Package Manager and run the following command.
Install-Package WebApiTestClient
You can always get the details about the package here.
Once you install the package, you can see some files are added to your Script and Area folder as preceding.
Script and Area Folder
Configuring WebApiTestClient
To configure the WebApiTestClient, please go to the folder Areas->Views->Help and then click on Api.cshtml
Api Cshtml
This is the view shown when you click on each API in your help page. Now add the preceding code block to that view.
@Html.DisplayForModel("TestClientDialogs")
@section Scripts
<
link
href
"~/Areas/HelpPage/HelpPage.css"
rel
"stylesheet"
type
"text/css"
/>
@Html.DisplayForModel("TestClientReferences")
Code Block
Testing WebApiTestClient
Now run your API application and go to the help page for any controller action, you can see a button called Test API on the bottom. If you click on that you will get a pop where you can test your API action.
Test API Client Output
Now if you send your request by clicking the send button, you will get an output as follows.
Test API Client Output With Response
You can always give id parameter as follows.
Test Client With Parameters
You can also give content-length and content-type in your post request as follows.
Test Client With Post
Test Client With PUT Request
References
Author has already posted the source code in GitHub, please check here.
Have a happy coding!.