Web API Documentation

Importance of Web API documentation

Web API documentation is really very helpful when two different team (Back end and Front end) are working on project and not sitting together so in that scenario you will send your API information through mail or call. What kind of parameter request contain. If you are making any changes in your web API every time you have to inform through mail or call.

So solution of above problem is generate web API documentation web page.

When you create a web API, it is often useful to create web API document web page, so that other developers will know how to call your API. You could create all the documentation manually, but it is better to autogenerate as much as possible.

So let us start with demo.
 
Step 1: In this  step we will create empty web API project. So open Visual Studio press CTRL + SHIFT + N as in the following image,

 
 

Step 2: 
Go to model folder add a class name as Student and it looks like this,  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace WebApi.Models   
  6. {  
  7.     public class Student   
  8.     {  
  9.         public int Id  
  10.       {  
  11.             get;  
  12.             set;  
  13.         }  
  14.         [Required]  
  15.         public string name   
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public string city  
  21.         {  
  22.             get;  
  23.             set;  
  24.         }  
  25.     }  
  26. }  
Build the project.
 
Add the Entity Framework into project  form Nuget Package Manger and open Package Manager Console (ALT+SHIFT +N + Enter). Then type
 
install-package EntityFramework    
 
and press Enter key. 
 
Step 3: Go to controller folder right click on it as in the following image,
 
 
 
 
 
Select the Student model class from dropdownlist and add a new Data Context and then click on add. This will generate the following code snippet, 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using WebApi.Models;  
  12. namespace WebApi.Controllers  
  13. {  
  14.     public class DemoController: ApiController  
  15.     {  
  16.         private WebApiContext db = new WebApiContext();  
  17.         // GET api/Demo  
  18.         public IQueryable < Student > GetStudents()  
  19.         {  
  20.                 return db.Students;  
  21.             }  
  22.             // GET api/Demo/5  
  23.             [ResponseType(typeof(Student))]  
  24.         public IHttpActionResult GetStudent(int id)  
  25.         {  
  26.                 Student student = db.Students.Find(id);  
  27.                 if (student == null) {  
  28.                     return NotFound();  
  29.                 }  
  30.                 return Ok(student);  
  31.             }  
  32.             // PUT api/Demo/5  
  33.         public IHttpActionResult PutStudent(int id, Student student)   
  34.         {  
  35.                 if (!ModelState.IsValid)  
  36.                 {  
  37.                     return BadRequest(ModelState);  
  38.                 }  
  39.                 if (id != student.Id)  
  40.                 {  
  41.                     return BadRequest();  
  42.                 }  
  43.                 db.Entry(student).State = EntityState.Modified;  
  44.                 try {  
  45.                     db.SaveChanges();  
  46.                     
  47.                 } catch (DbUpdateConcurrencyException)  
  48.                 {  
  49.                     if (!StudentExists(id))  
  50.                     {  
  51.                         return NotFound();  
  52.                     } else   
  53.                     {  
  54.                         throw;  
  55.                     }  
  56.                 }  
  57.                 return StatusCode(HttpStatusCode.NoContent);  
  58.             }  
  59.             // POST api/Demo  
  60.             [ResponseType(typeof(Student))]  
  61.         public IHttpActionResult PostStudent(Student student)  
  62.         {  
  63.                 if (!ModelState.IsValid)   
  64.                 {  
  65.                     return BadRequest(ModelState);  
  66.                 }  
  67.                 db.Students.Add(student);  
  68.                 db.SaveChanges();  
  69.                 return CreatedAtRoute("DefaultApi"new   
  70.                 {  
  71.                     id = student.Id  
  72.                 }, student);  
  73.             }  
  74.             // DELETE api/Demo/5  
  75.             [ResponseType(typeof(Student))]  
  76.         public IHttpActionResult DeleteStudent(int id)   
  77.         {  
  78.             Student student = db.Students.Find(id);  
  79.             if (student == null)  
  80.             {  
  81.                 return NotFound();  
  82.             }  
  83.             db.Students.Remove(student);  
  84.             db.SaveChanges();  
  85.             return Ok(student);  
  86.         }  
  87.         protected override void Dispose(bool disposing)   
  88.         {  
  89.             if (disposing)  
  90.             {  
  91.                 db.Dispose();  
  92.             }  
  93.             base.Dispose(disposing);  
  94.         }  
  95.         private bool StudentExists(int id)   
  96.         {  
  97.             return db.Students.Count(e => e.Id == id) > 0;  
  98.         }  
  99.     }  
  100. }  
CRUD operation created by scaffold.
 
Step 4: In this  step we will create web API document page.
 
Open Package Manager Console (CTRL +SHIFT + N +Enter)  and type the following command in console,
 
install-package Microsoft.AspNet.WebApi.HelpPage  
 
Above command installs the necessary assemblies and adds the MVC views for the help pages (located in the Areas/HelpPage folder). Now open the Global.asax file and register. Add the following code to the Application_Start method if it not there already, 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Http;  
  6. using System.Web.Mvc;  
  7. using System.Web.Routing;  
  8. namespace WebApi  
  9. {  
  10.     public class WebApiApplication: System.Web.HttpApplication   
  11.     {  
  12.         protected void Application_Start()  
  13.         {  
  14.             // Add this code, if not present.  
  15.             AreaRegistration.RegisterAllAreas();  
  16.             GlobalConfiguration.Configure(WebApiConfig.Register);  
  17.         }  
  18.     }  
  19. }  
  20. now open the file Areas / HelpPage / App_Start / HelpPageConfig.cs and go to Register method uncomment the following line:  
  21.   
  22.   
  23.     //Uncomment the following to use the documentation from XML documentation file.  
  24.     config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));  
Now enable XML documentation. In Solution Explorer, right-click the project and select Properties. Select the Build page.

 
Now open the DemoController and add some documentation comments (that describe your method) to the controller methods like the following, 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using WebApi.Models;  
  12. namespace WebApi.Controllers  
  13. {  
  14.     public class DemoController: ApiController  
  15.     {  
  16.         private WebApiContext db = new WebApiContext();  
  17.         /// <summary>  
  18.         /// Get all Student  
  19.         /// </summary>  
  20.         /// <returns>List of Student</returns>  
  21.         public IQueryable < Student > GetStudents()  
  22.         {  
  23.                 return db.Students;  
  24.             }  
  25.             /// <summary>  
  26.             /// Get student By ID  
  27.             /// </summary>  
  28.             /// <param name="id"> id</param>  
  29.             /// <returns>student object by id </returns>  
  30.             [ResponseType(typeof(Student))]  
  31.         public IHttpActionResult GetStudent(int id)   
  32.         {  
  33.                 Student student = db.Students.Find(id);  
  34.                 if (student == null)  
  35.                 {  
  36.                     return NotFound();  
  37.                 }  
  38.                 return Ok(student);  
  39.             }  
  40.             /// <summary>  
  41.             /// update the student  
  42.             /// </summary>  
  43.             /// <param name="id">id</param>  
  44.             /// <param name="student"></param>  
  45.             /// <returns>204</returns>  
  46.         public IHttpActionResult PutStudent(int id, Student student)  
  47.         {  
  48.                 if (!ModelState.IsValid)   
  49.                 {  
  50.                     return BadRequest(ModelState);  
  51.                 }  
  52.                 if (id != student.Id)   
  53.                 {  
  54.                     return BadRequest();  
  55.                 }  
  56.                 db.Entry(student).State = EntityState.Modified;  
  57.                 try {  
  58.                     db.SaveChanges();  
  59.                 } catch (DbUpdateConcurrencyException)  
  60.                 {  
  61.                     if (!StudentExists(id))   
  62.                     {  
  63.                         return NotFound();  
  64.                     } else   
  65.                     {  
  66.                         throw;  
  67.                     }  
  68.                 }  
  69.                 return StatusCode(HttpStatusCode.NoContent);  
  70.             }  
  71.             /// <summary>  
  72.             /// add student  
  73.             /// </summary>  
  74.             /// <param name="student">tsudent object</param>  
  75.             /// <returns>student object</returns>  
  76.             [ResponseType(typeof(Student))]  
  77.         public IHttpActionResult PostStudent(Student student)   
  78.         {  
  79.                 if (!ModelState.IsValid)  
  80.                 {  
  81.                     return BadRequest(ModelState);  
  82.                 }  
  83.                 db.Students.Add(student);  
  84.                 db.SaveChanges();  
  85.                 return CreatedAtRoute("DefaultApi"new  
  86.                 {  
  87.                     id = student.Id  
  88.                 }, student);  
  89.             }  
  90.             /// <summary>  
  91.             /// delete student  
  92.             /// </summary>  
  93.             /// <param name="id">id</param>  
  94.             /// <returns></returns>  
  95.             [ResponseType(typeof(Student))]  
  96.         public IHttpActionResult DeleteStudent(int id)   
  97.         {  
  98.             Student student = db.Students.Find(id);  
  99.             if (student == null)   
  100.             {  
  101.                 return NotFound();  
  102.             }  
  103.             db.Students.Remove(student);  
  104.             db.SaveChanges();  
  105.             return Ok(student);  
  106.         }  
  107.         protected override void Dispose(bool disposing)   
  108.         {  
  109.             if (disposing)  
  110.             {  
  111.                 db.Dispose();  
  112.             }  
  113.             base.Dispose(disposing);  
  114.         }  
  115.         private bool StudentExists(int id)  
  116.         {  
  117.             return db.Students.Count(e => e.Id == id) > 0;  
  118.         }  
  119.     }  
  120. }  
Step 5: Run the application, press F5 and type the url  http://localhost:portno/help  i.e. http://localhost:25316/help,
 
 
 
Click on post link you will see what parameters you have to pass. Here's the pic,
 
 
In same way you can see for all method. 
 
Step 6:  Suppose you want to hide all controller methods or particular method from document page then use the following code.   
 
For hiding all controller method decorate the controller,
  1. [ApiExplorerSettings(IgnoreApi = true)]  
  2. public class DemoController: ApiController {}  
For particular method use the following code, 
  1. public class DemoController: ApiController   
  2. {  
  3.     private WebApiContext db = new WebApiContext();  
  4.     /// <summary>  
  5.     /// Get all Student  
  6.     /// </summary>  
  7.     /// <returns>List of Student</returns>  
  8.     ///  
  9.     [ApiExplorerSettings(IgnoreApi = true)]  
  10.     public IQueryable < Student > GetStudents()   
  11.     {  
  12.         return db.Students;  
  13.     }  
  14. }


Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles