Site icon Sibeesh Passion

Working with API help page controller action description in Web API

In this article we are going to see how we can enable the API descriptions for the better understanding of how our API controller works and what exactly it is supposed to do. It is recommended that to give the summary and parameter lists and a bit introduction to the service whenever you write any API services. Here I am going to use create a Web API in Visual Studio 2015. I hope you will like this.

Download the source code

You can always download the source code here: API Help Page Documentation

Background

Few months back I have hosted one of my API application to Azure. I thought of implementing the document summary for the services(controllers actions) now. And I did, now any one can understand what exactly my service will do by going to the help page of the API application. I will show you a demo of the same. Here we will create a Web API with entity framework. Lets us start then.

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

[sql]
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 ON
( NAME = N’TrialsDB_log’, FILENAME = N’C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf’ , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO

ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110
GO

IF (1 = FULLTEXTSERVICEPROPERTY(‘IsFullTextInstalled’))
begin
EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = ‘enable’
end
GO

ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF
GO

ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF
GO

ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF
GO

ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF
GO

ALTER DATABASE [TrialsDB] SET ARITHABORT OFF
GO

ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF
GO

ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON
GO

ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF
GO

ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON
GO

ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF
GO

ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL
GO

ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF
GO

ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF
GO

ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF
GO

ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF
GO

ALTER DATABASE [TrialsDB] SET DISABLE_BROKER
GO

ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO

ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF
GO

ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF
GO

ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO

ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE
GO

ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF
GO

ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF
GO

ALTER DATABASE [TrialsDB] SET RECOVERY FULL
GO

ALTER DATABASE [TrialsDB] SET MULTI_USER
GO

ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM
GO

ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF
GO

ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO

ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO

ALTER DATABASE [TrialsDB] SET READ_WRITE
GO
[/sql]

Create table with data

[sql]
USE [TrialsDB]
GO
/****** Object: Table [dbo].[Product] Script Date: 5/12/2016 10:54:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
[ProductID] [int] NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[ProductNumber] [nvarchar](25) NOT NULL,
[MakeFlag] [bit] NOT NULL,
[FinishedGoodsFlag] [bit] NOT NULL,
[Color] [nvarchar](15) NULL,
[SafetyStockLevel] [smallint] NOT NULL,
[ReorderPoint] [smallint] NOT NULL,
[StandardCost] [money] NOT NULL,
[ListPrice] [money] NOT NULL,
[Size] [nvarchar](5) NULL,
[SizeUnitMeasureCode] [nchar](3) NULL,
[WeightUnitMeasureCode] [nchar](3) NULL,
[Weight] [decimal](8, 2) NULL,
[DaysToManufacture] [int] NOT NULL,
[ProductLine] [nchar](2) NULL,
[Class] [nchar](2) NULL,
[Style] [nchar](2) NULL,
[ProductSubcategoryID] [int] NULL,
[ProductModelID] [int] NULL,
[SellStartDate] [datetime] NOT NULL,
[SellEndDate] [datetime] NULL,
[DiscontinuedDate] [datetime] NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ModifiedDate] [datetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (1, N’Adjustable Race’, N’AR-5381′, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’694215b7-08f7-4c0d-acb1-d734ba44c0c8′, CAST(0x00009A5C00A53CF8 AS DateTime))
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (2, N’Bearing Ball’, N’BA-8327′, 0, 0, NULL, 1000, 750, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’58ae3c20-4f3a-4749-a7d4-d568806cc537′, CAST(0x00009A5C00A53CF8 AS DateTime))
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (3, N’BB Ball Bearing’, N’BE-2349′, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e’, CAST(0x00009A5C00A53CF8 AS DateTime))
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (4, N’Headset Ball Bearings’, N’BE-2908′, 0, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’ecfed6cb-51ff-49b5-b06c-7d8ac834db8b’, CAST(0x00009A5C00A53CF8 AS DateTime))
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (316, N’Blade’, N’BL-2036′, 1, 0, NULL, 800, 600, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’e73e9750-603b-4131-89f5-3dd15ed5ff80′, CAST(0x00009A5C00A53CF8 AS DateTime))
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (317, N’LL Crankarm’, N’CA-5965′, 0, 0, N’Black’, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N’L ‘, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’3c9d10b7-a6b2-4774-9963-c19dcee72fea’, CAST(0x00009A5C00A53CF8 AS DateTime))
INSERT [dbo].[Product] ([ProductID], [Name], [ProductNumber], [MakeFlag], [FinishedGoodsFlag], [Color], [SafetyStockLevel], [ReorderPoint], [StandardCost], [ListPrice], [Size], [SizeUnitMeasureCode], [WeightUnitMeasureCode], [Weight], [DaysToManufacture], [ProductLine], [Class], [Style], [ProductSubcategoryID], [ProductModelID], [SellStartDate], [SellEndDate], [DiscontinuedDate], [rowguid], [ModifiedDate]) VALUES (318, N’ML Crankarm’, N’CA-6738′, 0, 0, N’Black’, 500, 375, 0.0000, 0.0000, NULL, NULL, NULL, NULL, 0, NULL, N’M ‘, NULL, NULL, NULL, CAST(0x0000921E00000000 AS DateTime), NULL, NULL, N’eabb9a92-fa07-4eab-8955-f0517b4a4ca7’, CAST(0x00009A5C00A53CF8 AS DateTime))
[/sql]

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 like preceding has been generated for you.

[csharp]
public class ProductsController : ApiController
{
private TrialsDBEntities db = new TrialsDBEntities();

// GET: api/Products
public IQueryable<Product> GetProducts()
{
return db.Products;
}

// GET: api/Products/5
[ResponseType(typeof(Product))]
public IHttpActionResult GetProduct(int id)
{
Product product = db.Products.Find(id);
if (product == null)
{
return NotFound();
}

return Ok(product);
}

// PUT: api/Products/5
[ResponseType(typeof(void))]
public IHttpActionResult PutProduct(int id, Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

if (id != product.ProductID)
{
return BadRequest();
}

db.Entry(product).State = EntityState.Modified;

try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}

return StatusCode(HttpStatusCode.NoContent);
}

// POST: api/Products
[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

db.Products.Add(product);

try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (ProductExists(product.ProductID))
{
return Conflict();
}
else
{
throw;
}
}

return CreatedAtRoute("DefaultApi", new { id = product.ProductID }, product);
}

// DELETE: api/Products/5
[ResponseType(typeof(Product))]
public IHttpActionResult DeleteProduct(int id)
{
Product product = db.Products.Find(id);
if (product == null)
{
return NotFound();
}

db.Products.Remove(product);
db.SaveChanges();

return Ok(product);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}

private bool ProductExists(int id)
{
return db.Products.Count(e => e.ProductID == id) > 0;
}
}
[/csharp]

Now please run your application and go to the help page. You can see the API help page as follows.

API Help Page

As you can see ‘No documentation available.’ under description of all the service actions. No worries we will try to add some summary to the actions now. So we will change the code as follows.

[csharp]
#region GetProducts
/// <summary>
/// Get all the products available
/// GET: api/Products
/// </summary>
public IQueryable<Product> GetProducts()
{
return db.Products;
}
#endregion

#region GetProductWithParameter
/// <summary>
/// Get a single product
/// GET: api/Products/5
/// <param name="id"></param>
/// </summary>
[ResponseType(typeof(Product))]
public IHttpActionResult GetProduct(int id)
{
Product product = db.Products.Find(id);
if (product == null)
{
return NotFound();
}

return Ok(product);
}
#endregion
[/csharp]

Now run your application and see the help page. Still the same result? Hmm, here comes the things we need to do. I will explain that.

  • Go to Areas\HelpPage\App_Start and click on the file HelpPageConfig.cs.
  • Uncomment the following line from the static function Register.
  • [csharp]
    config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("App_Data/XmlDocument.xml")));
    [/csharp]

  • Right click on your project and go to properties, then click on Build
  • Go to Output section and click on XML documentation file and then type ~/App_Data/XmlDocument.xml in the given text box.
  • Save and build your project.
  • This will create a XML document with the name XmlDocument.xml in App_Data folder. Once it is generated, the summary you have described in your API controller will be listed there. Initially the file will be in excluded state, you may need to include the same to your project when you deploy your API application. For that please follows the below steps.

  • Click on show all files.
  • Click on Refresh.
  • Go to App_Data folder and find XmlDocument.xml.
  • Right click the file and click Include In Project.
  • That’s all. Run your application and see the Help page again. Hope you get the page as follows.

    API Help Page With Descriptions

    Have a happy coding!.

    Conclusion

    Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

    Your turn. What do you think?

    A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

    Kindest Regards
    Sibeesh Venu

    Exit mobile version