Working With API Help Page Controller In Web API

In this article we are going to see how we can enable the API descriptions for a better understanding of how our API controller works and what exactly it is supposed to do. It is recommended to give the summary and parameter lists and a bit of an 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.

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

Background

A few months back I hosted one of my API applications 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.
Please see this article in my blog here

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
  1. USE [master] GO /****** Object: Database [TrialsDB] Script Date: 5/12/2016 10:56:41 AM ******/  
  2. CREATE DATABASE [TrialsDB] CONTAINMENT = NONE ON PRIMARY (NAME = N'TrialsDB',  
  3.                                          FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf',  
  4.                                          SIZE = 3072KB,  
  5.                                          MAXSIZE = UNLIMITED,  
  6.                                          FILEGROWTH = 1024KB) LOG ON (NAME = N'TrialsDB_log',  
  7.                                          FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf',  
  8.                                                                                                                                       SIZE = 1024KB,  
  9.                                                                                                                                              MAXSIZE = 2048GB,  
  10.                                                                                                                                              FILEGROWTH = 10%) GO  
  11. ALTER DATABASE [TrialsDB]  
  12. SET COMPATIBILITY_LEVEL = 110 GO IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) BEGIN EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable' END GO  
  13. ALTER DATABASE [TrialsDB]  
  14. SET ANSI_NULL_DEFAULT OFF GO  
  15. ALTER DATABASE [TrialsDB]  
  16. SET ANSI_NULLS OFF GO  
  17. ALTER DATABASE [TrialsDB]  
  18. SET ANSI_PADDING OFF GO  
  19. ALTER DATABASE [TrialsDB]  
  20. SET ANSI_WARNINGS OFF GO  
  21. ALTER DATABASE [TrialsDB]  
  22. SET ARITHABORT OFF GO  
  23. ALTER DATABASE [TrialsDB]  
  24. SET AUTO_CLOSE OFF GO  
  25. ALTER DATABASE [TrialsDB]  
  26. SET AUTO_CREATE_STATISTICS ON GO  
  27. ALTER DATABASE [TrialsDB]  
  28. SET AUTO_SHRINK OFF GO  
  29. ALTER DATABASE [TrialsDB]  
  30. SET AUTO_UPDATE_STATISTICS ON GO  
  31. ALTER DATABASE [TrialsDB]  
  32. SET CURSOR_CLOSE_ON_COMMIT OFF GO  
  33. ALTER DATABASE [TrialsDB]  
  34. SET CURSOR_DEFAULT GLOBAL GO  
  35. ALTER DATABASE [TrialsDB]  
  36. SET CONCAT_NULL_YIELDS_NULL OFF GO  
  37. ALTER DATABASE [TrialsDB]  
  38. SET NUMERIC_ROUNDABORT OFF GO  
  39. ALTER DATABASE [TrialsDB]  
  40. SET QUOTED_IDENTIFIER OFF GO  
  41. ALTER DATABASE [TrialsDB]  
  42. SET RECURSIVE_TRIGGERS OFF GO  
  43. ALTER DATABASE [TrialsDB]  
  44. SET DISABLE_BROKER GO  
  45. ALTER DATABASE [TrialsDB]  
  46. SET AUTO_UPDATE_STATISTICS_ASYNC OFF GO  
  47. ALTER DATABASE [TrialsDB]  
  48. SET DATE_CORRELATION_OPTIMIZATION OFF GO  
  49. ALTER DATABASE [TrialsDB]  
  50. SET TRUSTWORTHY OFF GO  
  51. ALTER DATABASE [TrialsDB]  
  52. SET ALLOW_SNAPSHOT_ISOLATION OFF GO  
  53. ALTER DATABASE [TrialsDB]  
  54. SET PARAMETERIZATION SIMPLE GO  
  55. ALTER DATABASE [TrialsDB]  
  56. SET READ_COMMITTED_SNAPSHOT OFF GO  
  57. ALTER DATABASE [TrialsDB]  
  58. SET HONOR_BROKER_PRIORITY OFF GO  
  59. ALTER DATABASE [TrialsDB]  
  60. SET RECOVERY FULL GO  
  61. ALTER DATABASE [TrialsDB]  
  62. SET MULTI_USER GO  
  63. ALTER DATABASE [TrialsDB]  
  64. SET PAGE_VERIFY CHECKSUM GO  
  65. ALTER DATABASE [TrialsDB]  
  66. SET DB_CHAINING OFF GO  
  67. ALTER DATABASE [TrialsDB]  
  68. SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF) GO  
  69. ALTER DATABASE [TrialsDB]  
  70. SET TARGET_RECOVERY_TIME = 0 SECONDS GO  
  71. ALTER DATABASE [TrialsDB]  
  72. SET READ_WRITE GO 

Create table with data

  1. USE [TrialsDB] GO  
  2. /****** Object: Table [dbo].[Product] Script Date: 5/12/2016 10:54:48 AM ******/  
  3. SET  
  4. ANSI_NULLS ON GO  
  5. SET  
  6. QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Product](  
  7.    [ProductID] [intNOT NULL,  
  8.    [Name] [nvarchar](MAXNOT NULL,  
  9.    [ProductNumber] [nvarchar](25) NOT NULL,  
  10.    [MakeFlag] [bitNOT NULL,  
  11.    [FinishedGoodsFlag] [bitNOT NULL,  
  12.    [Color] [nvarchar](15) NULL,  
  13.    [SafetyStockLevel] [smallintNOT NULL,  
  14.    [ReorderPoint] [smallintNOT NULL,  
  15.    [StandardCost] [money] NOT NULL,  
  16.    [ListPrice] [money] NOT NULL,  
  17.    [Size] [nvarchar](5) NULL,  
  18.    [SizeUnitMeasureCode] [nchar](3) NULL,  
  19.    [WeightUnitMeasureCode] [nchar](3) NULL,  
  20.    [Weight] [decimal](8, 2) NULL,  
  21.    [DaysToManufacture] [intNOT NULL,  
  22.    [ProductLine] [nchar](2) NULL,  
  23.    [Class] [nchar](2) NULL,  
  24.    [Style] [nchar](2) NULL,  
  25.    [ProductSubcategoryID] [intNULL,  
  26.    [ProductModelID] [intNULL,  
  27.    [SellStartDate] [datetime] NOT NULL,  
  28.    [SellEndDate] [datetime] NULL,  
  29.    [DiscontinuedDate] [datetime] NULL,  
  30.    [rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,  
  31.    [ModifiedDate] [datetime] NOT NULL  
  32. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO INSERT [dbo].[Product] (  
  33.    [ProductID], [Name], [ProductNumber],  
  34.    [MakeFlag], [FinishedGoodsFlag],  
  35.    [Color], [SafetyStockLevel], [ReorderPoint],  
  36.    [StandardCost], [ListPrice], [Size],  
  37.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  38.    [Weight], [DaysToManufacture], [ProductLine],  
  39.    [Class], [Style], [ProductSubcategoryID],  
  40.    [ProductModelID], [SellStartDate],  
  41.    [SellEndDate], [DiscontinuedDate],  
  42.    [rowguid], [ModifiedDate]  
  43. )  
  44. VALUES  
  45. (  
  46.    1,  
  47.    N 'Adjustable Race',  
  48.    N 'AR-5381',  
  49.    0,  
  50.    0,  
  51.    NULL,  
  52.    1000,  
  53.    750,  
  54.    0.0000,  
  55.    0.0000,  
  56.    NULL,  
  57.    NULL,  
  58.    NULL,  
  59.    NULL,  
  60.    0,  
  61.    NULL,  
  62.    NULL,  
  63.    NULL,  
  64.    NULL,  
  65.    NULL,  
  66.    CAST(0x0000921E00000000 AS DateTime),  
  67.    NULL,  
  68.    NULL,  
  69.    N '694215b7-08f7-4c0d-acb1-d734ba44c0c8',  
  70.    CAST(0x00009A5C00A53CF8 AS DateTime)  
  71. INSERT [dbo].[Product] (  
  72.    [ProductID], [Name], [ProductNumber],  
  73.    [MakeFlag], [FinishedGoodsFlag],  
  74.    [Color], [SafetyStockLevel], [ReorderPoint],  
  75.    [StandardCost], [ListPrice], [Size],  
  76.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  77.    [Weight], [DaysToManufacture], [ProductLine],  
  78.    [Class], [Style], [ProductSubcategoryID],  
  79.    [ProductModelID], [SellStartDate],  
  80.    [SellEndDate], [DiscontinuedDate],  
  81.    [rowguid], [ModifiedDate]  
  82. )  
  83. VALUES  
  84. (  
  85.    2,  
  86.    N 'Bearing Ball',  
  87.    N 'BA-8327',  
  88.    0,  
  89.    0,  
  90.    NULL,  
  91.    1000,  
  92.    750,  
  93.    0.0000,  
  94.    0.0000,  
  95.    NULL,  
  96.    NULL,  
  97.    NULL,  
  98.    NULL,  
  99.    0,  
  100.    NULL,  
  101.    NULL,  
  102.    NULL,  
  103.    NULL,  
  104.    NULL,  
  105.    CAST(0x0000921E00000000 AS DateTime),  
  106.    NULL,  
  107.    NULL,  
  108.    N '58ae3c20-4f3a-4749-a7d4-d568806cc537',  
  109.    CAST(0x00009A5C00A53CF8 AS DateTime)  
  110. INSERT [dbo].[Product] (  
  111.    [ProductID], [Name], [ProductNumber],  
  112.    [MakeFlag], [FinishedGoodsFlag],  
  113.    [Color], [SafetyStockLevel], [ReorderPoint],  
  114.    [StandardCost], [ListPrice], [Size],  
  115.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  116.    [Weight], [DaysToManufacture], [ProductLine],  
  117.    [Class], [Style], [ProductSubcategoryID],  
  118.    [ProductModelID], [SellStartDate],  
  119.    [SellEndDate], [DiscontinuedDate],  
  120.    [rowguid], [ModifiedDate]  
  121. )  
  122. VALUES  
  123. (  
  124.    3,  
  125.    N 'BB Ball Bearing',  
  126.    N 'BE-2349',  
  127.    1,  
  128.    0,  
  129.    NULL,  
  130.    800,  
  131.    600,  
  132.    0.0000,  
  133.    0.0000,  
  134.    NULL,  
  135.    NULL,  
  136.    NULL,  
  137.    NULL,  
  138.    1,  
  139.    NULL,  
  140.    NULL,  
  141.    NULL,  
  142.    NULL,  
  143.    NULL,  
  144.    CAST(0x0000921E00000000 AS DateTime),  
  145.    NULL,  
  146.    NULL,  
  147.    N '9c21aed2-5bfa-4f18-bcb8-f11638dc2e4e',  
  148.    CAST(0x00009A5C00A53CF8 AS DateTime)  
  149. INSERT [dbo].[Product] (  
  150.    [ProductID], [Name], [ProductNumber],  
  151.    [MakeFlag], [FinishedGoodsFlag],  
  152.    [Color], [SafetyStockLevel], [ReorderPoint],  
  153.    [StandardCost], [ListPrice], [Size],  
  154.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  155.    [Weight], [DaysToManufacture], [ProductLine],  
  156.    [Class], [Style], [ProductSubcategoryID],  
  157.    [ProductModelID], [SellStartDate],  
  158.    [SellEndDate], [DiscontinuedDate],  
  159.    [rowguid], [ModifiedDate]  
  160. )  
  161. VALUES  
  162. (  
  163.    4,  
  164.    N 'Headset Ball Bearings',  
  165.    N 'BE-2908',  
  166.    0,  
  167.    0,  
  168.    NULL,  
  169.    800,  
  170.    600,  
  171.    0.0000,  
  172.    0.0000,  
  173.    NULL,  
  174.    NULL,  
  175.    NULL,  
  176.    NULL,  
  177.    0,  
  178.    NULL,  
  179.    NULL,  
  180.    NULL,  
  181.    NULL,  
  182.    NULL,  
  183.    CAST(0x0000921E00000000 AS DateTime),  
  184.    NULL,  
  185.    NULL,  
  186.    N 'ecfed6cb-51ff-49b5-b06c-7d8ac834db8b',  
  187.    CAST(0x00009A5C00A53CF8 AS DateTime)  
  188. INSERT [dbo].[Product] (  
  189.    [ProductID], [Name], [ProductNumber],  
  190.    [MakeFlag], [FinishedGoodsFlag],  
  191.    [Color], [SafetyStockLevel], [ReorderPoint],  
  192.    [StandardCost], [ListPrice], [Size],  
  193.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  194.    [Weight], [DaysToManufacture], [ProductLine],  
  195.    [Class], [Style], [ProductSubcategoryID],  
  196.    [ProductModelID], [SellStartDate],  
  197.    [SellEndDate], [DiscontinuedDate],  
  198.    [rowguid], [ModifiedDate]  
  199. )  
  200. VALUES  
  201. (  
  202.    316,  
  203.    N 'Blade',  
  204.    N 'BL-2036',  
  205.    1,  
  206.    0,  
  207.    NULL,  
  208.    800,  
  209.    600,  
  210.    0.0000,  
  211.    0.0000,  
  212.    NULL,  
  213.    NULL,  
  214.    NULL,  
  215.    NULL,  
  216.    1,  
  217.    NULL,  
  218.    NULL,  
  219.    NULL,  
  220.    NULL,  
  221.    NULL,  
  222.    CAST(0x0000921E00000000 AS DateTime),  
  223.    NULL,  
  224.    NULL,  
  225.    N 'e73e9750-603b-4131-89f5-3dd15ed5ff80',  
  226.    CAST(0x00009A5C00A53CF8 AS DateTime)  
  227. INSERT [dbo].[Product] (  
  228.    [ProductID], [Name], [ProductNumber],  
  229.    [MakeFlag], [FinishedGoodsFlag],  
  230.    [Color], [SafetyStockLevel], [ReorderPoint],  
  231.    [StandardCost], [ListPrice], [Size],  
  232.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  233.    [Weight], [DaysToManufacture], [ProductLine],  
  234.    [Class], [Style], [ProductSubcategoryID],  
  235.    [ProductModelID], [SellStartDate],  
  236.    [SellEndDate], [DiscontinuedDate],  
  237.    [rowguid], [ModifiedDate]  
  238. )  
  239. VALUES  
  240. (  
  241.    317,  
  242.    N 'LL Crankarm',  
  243.    N 'CA-5965',  
  244.    0,  
  245.    0,  
  246.    N 'Black',  
  247.    500,  
  248.    375,  
  249.    0.0000,  
  250.    0.0000,  
  251.    NULL,  
  252.    NULL,  
  253.    NULL,  
  254.    NULL,  
  255.    0,  
  256.    NULL,  
  257.    N 'L ',  
  258.    NULL,  
  259.    NULL,  
  260.    NULL,  
  261.    CAST(0x0000921E00000000 AS DateTime),  
  262.    NULL,  
  263.    NULL,  
  264.    N '3c9d10b7-a6b2-4774-9963-c19dcee72fea',  
  265.    CAST(0x00009A5C00A53CF8 AS DateTime)  
  266. INSERT [dbo].[Product] (  
  267.    [ProductID], [Name], [ProductNumber],  
  268.    [MakeFlag], [FinishedGoodsFlag],  
  269.    [Color], [SafetyStockLevel], [ReorderPoint],  
  270.    [StandardCost], [ListPrice], [Size],  
  271.    [SizeUnitMeasureCode], [WeightUnitMeasureCode],  
  272.    [Weight], [DaysToManufacture], [ProductLine],  
  273.    [Class], [Style], [ProductSubcategoryID],  
  274.    [ProductModelID], [SellStartDate],  
  275.    [SellEndDate], [DiscontinuedDate],  
  276.    [rowguid], [ModifiedDate]  
  277. )  
  278. VALUES  
  279. (  
  280.    318,  
  281.    N 'ML Crankarm',  
  282.    N 'CA-6738',  
  283.    0,  
  284.       0,  
  285.    N 'Black',  
  286.    500,  
  287.    375,  
  288.    0.0000,  
  289.    0.0000,  
  290.    NULL,  
  291.    NULL,  
  292.    NULL,  
  293.    NULL,  
  294.    0,  
  295.    NULL,  
  296.    N 'M ',  
  297.    NULL,  
  298.    NULL,  
  299.    NULL,  
  300.    CAST(0x0000921E00000000 AS DateTime),  
  301.    NULL,  
  302.    NULL,  
  303.    N 'eabb9a92-fa07-4eab-8955-f0517b4a4ca7',  
  304.    CAST(0x00009A5C00A53CF8 AS DateTime)  

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 the preceding one has been generated for you.
  1. public class ProductsController : ApiController  
  2. {  
  3.     private TrialsDBEntities db = new TrialsDBEntities();  
  4.     // GET: api/Products  
  5.     public IQueryable<Product> GetProducts()  
  6.     {  
  7.         return db.Products;  
  8.     }  
  9.     // GET: api/Products/5  
  10.     [ResponseType(typeof(Product))]  
  11.     public IHttpActionResult GetProduct(int id)  
  12.     {  
  13.         Product product = db.Products.Find(id);  
  14.         if (product == null)  
  15.         {  
  16.             return NotFound();  
  17.         }  
  18.         return Ok(product);  
  19.     }  
  20.     // PUT: api/Products/5  
  21.     [ResponseType(typeof(void))]  
  22.     public IHttpActionResult PutProduct(int id, Product product)  
  23.     {  
  24.         if (!ModelState.IsValid)  
  25.         {  
  26.             return BadRequest(ModelState);  
  27.         }  
  28.         if (id != product.ProductID)  
  29.         {  
  30.             return BadRequest();  
  31.         }  
  32.         db.Entry(product).State = EntityState.Modified;  
  33.         try  
  34.         {  
  35.             db.SaveChanges();  
  36.         }  
  37.         catch (DbUpdateConcurrencyException)  
  38.         {  
  39.             if (!ProductExists(id))  
  40.             {  
  41.                 return NotFound();  
  42.             }  
  43.             else  
  44.             {  
  45.                 throw;  
  46.             }  
  47.         }  
  48.         return StatusCode(HttpStatusCode.NoContent);  
  49.     }  
  50.     // POST: api/Products  
  51.     [ResponseType(typeof(Product))]  
  52.     public IHttpActionResult PostProduct(Product product)  
  53.     {  
  54.         if (!ModelState.IsValid)  
  55.         {  
  56.             return BadRequest(ModelState);  
  57.         }  
  58.         db.Products.Add(product);  
  59.         try  
  60.         {  
  61.             db.SaveChanges();  
  62.         }  
  63.         catch (DbUpdateException)  
  64.         {  
  65.             if (ProductExists(product.ProductID))  
  66.             {  
  67.                 return Conflict();  
  68.             }  
  69.             else  
  70.             {  
  71.                 throw;  
  72.             }  
  73.         }  
  74.         return CreatedAtRoute("DefaultApi"new  
  75.         {  
  76.             id = product.ProductID  
  77.         }, product);  
  78.     }  
  79.     // DELETE: api/Products/5  
  80.     [ResponseType(typeof(Product))]  
  81.     public IHttpActionResult DeleteProduct(int id)  
  82.     {  
  83.         Product product = db.Products.Find(id);  
  84.         if (product == null)  
  85.         {  
  86.             return NotFound();  
  87.         }  
  88.         db.Products.Remove(product);  
  89.         db.SaveChanges();  
  90.         return Ok(product);  
  91.     }  
  92.     protected override void Dispose(bool disposing)  
  93.     {  
  94.         if (disposing)  
  95.         {  
  96.             db.Dispose();  
  97.         }  
  98.         base.Dispose(disposing);  
  99.     }  
  100.     private bool ProductExists(int id)  
  101.     {  
  102.         return db.Products.Count(e => e.ProductID == id) > 0;  
  103.     }  

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.
  1. #region GetProducts  
  2. /// <summary>  
  3. /// Get all the products available  
  4. /// GET: api/Products  
  5. /// </summary>  
  6. public IQueryable<Product> GetProducts()  
  7. {  
  8.     return db.Products;  
  9. }  
  10. #endregion  
  11. #region GetProductWithParameter  
  12. /// <summary>  
  13. /// Get a single product  
  14. /// GET: api/Products/5  
  15. /// <param name="id"></param>  
  16. /// </summary>  
  17. [ResponseType(typeof(Product))]  
  18. public IHttpActionResult GetProduct(int id)  
  19. {  
  20.     Product product = db.Products.Find(id);  
  21.     if (product == null)  
  22.     {  
  23.         return NotFound();  
  24.     }  
  25.     return Ok(product);  
  26. }  
  27. #endregion 
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.
    1. config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("App_Data/XmlDocument.xml"))); 

  • 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 is needed? Did you find this post useful? I hope you liked this article. Please share with 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.


Similar Articles