ASP.NET Core 3.1 Web API and Swagger

Introduction

 
ASP.NET Web API and ASP.NET MVC previously had separate types and setups, but the Web API from ASP.NET Core is the same as the one from ASP.NET Core MVC. The Web API offers a simple communication way based on Representational State Transfer (REST). With REST, HTTP verbs such as GET, POST, PUT, and DELETE is used. GET is used to retrieve resources, POST is used to add new resources, PUT is used to update resources, and DELETE is used to delete resources.
 

Building Services

 
Using .NET Core, you need to start with an ASP.NET Core Web Application and select the Web API in the following dialog. This template adds folders and references needed with the Web API. The directory structure that is created with this template contains folders that are needed for creating the services. The Controllers directory contains the Web API controllers, Web API, and ASP.NET Core MVC makes use of the same infrastructure.
 
ASP.NET Core 3.1 Web API And Swagger
 

Section 1

 
Create a PlaceInfo datatable in MSSQL. Also, it creates a class PlaceInfo in the model folder.
 
 PlaceInfo Table Structure
  1. CREATE TABLE [dbo].[PlaceInfo](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Place] [varchar](50) NOT NULL,  
  4.     [About] [varchar](300) NOT NULL,  
  5.     [City] [varchar](20) NOT NULL,  
  6.     [State] [varchar](20) NOT NULL,  
  7.     [Country] [varchar](20) NOT NULL,  
  8.  CONSTRAINT [PK_PlaceInfo] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [Id] ASC  
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,   
  12. IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  13. ON [PRIMARY]  
 
 PlaceInfo Class
  1. public class PlaceInfo  
  2. {  
  3.     public int Id { getset; }  
  4.     [Required]  
  5.     public string Place { getset; }  
  6.     [Required]  
  7.     public string About { getset; }  
  8.     [Required]  
  9.     public string City { getset; }  
  10.     [Required]  
  11.     public string State { getset; }  
  12.     [Required]  
  13.     public string Country { getset; }  
  14. }
 
Create a Services folder in project and add two classes, one is for interface IPlaceInfoService and add method in interface Add(),AddRange(),GetAll(),Find(),Remove() & Update(). Second create PlaceInfoService class is derived from IPlaceInfoService interface. This defines the body of all interface methods, Add(), AddRange(), GetAll(), Find(), Remove() & Update() in PlaceInfoService class. 
  1. public interface IPlaceInfoService  
  2. {  
  3.     int Add(PlaceInfo placeInfo);  
  4.     int AddRange(IEnumerable<PlaceInfo> places);  
  5.     IEnumerable<PlaceInfo> GetAll();  
  6.     PlaceInfo Find(int id);  
  7.     int Remove(int id);  
  8.     int Update(PlaceInfo placeInfo);  
  9. }  
  10.   
  11. public class PlaceInfoService : IPlaceInfoService  
  12. {  
  13.     public int Add(PlaceInfo placeInfo)  
  14.     {  
  15.         string sQry = "INSERT INTO [PlaceInfo] ([Place],[About],[City],[State],[Country]) " +  
  16.             "VALUES('" + placeInfo.Place + "','" + placeInfo.About + "','" + placeInfo.City + "','" +   
  17.             placeInfo.State + "','" + placeInfo.Country + "')";  
  18.         int retVal=ExecuteCRUDByQuery(sQry);  
  19.         return retVal;  
  20.     }  
  21.   
  22.     public int AddRange(IEnumerable<PlaceInfo> places)  
  23.     {  
  24.         string sQry = "INSERT INTO [PlaceInfo] ([Place],[About],[City],[State],[Country]) VALUES";  
  25.         string sVal = "";  
  26.         foreach(var place in places)              
  27.           sVal+= "('" + place.Place + "','" + place.About + "','" + place.City + "','" + place.State + "','" + place.Country + "'),";  
  28.         sVal = sVal.TrimEnd(',');  
  29.         sQry = sQry + sVal;  
  30.         int retVal=ExecuteCRUDByQuery(sQry);  
  31.         return retVal;  
  32.     }  
  33.   
  34.     public PlaceInfo Find(int id)  
  35.     {  
  36.         PlaceInfo placeInfo = null;  
  37.         string sQry = "SELECT * FROM [PlaceInfo] WHERE [Id]="+id;  
  38.         DataTable dtPlaceInfo = ExecuteQuery(sQry);  
  39.         if (dtPlaceInfo != null)  
  40.         {  
  41.             DataRow dr = dtPlaceInfo.Rows[0];  
  42.             placeInfo = GetPlaceInfoByRow(dr);  
  43.         }  
  44.         return placeInfo;  
  45.     }  
  46.   
  47.     public IEnumerable<PlaceInfo> GetAll()  
  48.     {  
  49.         List<PlaceInfo> placeInfos = null;  
  50.         string sQry = "SELECT * FROM [PlaceInfo]";  
  51.         DataTable dtPlaceInfo = ExecuteQuery(sQry);             
  52.         if (dtPlaceInfo != null)  
  53.         {  
  54.             placeInfos = new List<PlaceInfo>();  
  55.             foreach (DataRow dr in dtPlaceInfo.Rows)  
  56.               placeInfos.Add(GetPlaceInfoByRow(dr));  
  57.         }  
  58.         return placeInfos;  
  59.     }  
  60.   
  61.     public int Remove(int id)  
  62.     {  
  63.         string sQry = "DELETE FROM [PlaceInfo] WHERE [Id]=" + id;  
  64.         int retVal=ExecuteCRUDByQuery(sQry);  
  65.         return retVal;  
  66.     }  
  67.   
  68.     public int Update(PlaceInfo placeInfo)  
  69.     {  
  70.         string sQry = "UPDATE [PlaceInfo] SET [Place]='" + placeInfo.Place + "',[About]='" + placeInfo.About + "',[City]='" + placeInfo.City + "',[State]='" + placeInfo.State + "',[Country]='" + placeInfo.Country + "' WHERE [Id]=" + placeInfo.Id;  
  71.         int retVal=ExecuteCRUDByQuery(sQry);  
  72.         return retVal;              
  73.     }  
  74.    // code detail is below  
  75.     private int ExecuteCRUDByQuery(string strSql){  }  
  76.     private DataTable ExecuteQuery(string strSql){  }  
  77.     private PlaceInfo GetPlaceInfoByRow(DataRow dr){  }  
  78.   
  79. }  
Created three private functions which are named ExecuteCRUDByQuery,ExecuteQuery and GetPlaceInfoByRow. All three functions are used to communicate with theSQL database server. The first function ExecuteCRUDByQuery is used to insert, update and delete record in datatable by passing SQL query. The second function ExecuteQuery is used to get records from datatable by passing sql query. Function GetPlaceInfoByRow is used to get records from datarow to PlaceInfo model class.
  1. private int ExecuteCRUDByQuery(string strSql)  
  2. {  
  3.     string sConStr = "Data Source=.\\SQLExpress;Initial Catalog=YourDB;Integrated Security=True";  
  4.     SqlConnection conn = null;  
  5.     int iR = 0;  
  6.     try  
  7.     {  
  8.         conn = new SqlConnection(sConStr);  
  9.         SqlCommand cmd = new SqlCommand(strSql, conn);  
  10.         cmd.CommandType = CommandType.Text;  
  11.         conn.Open();  
  12.         //Execute the command  
  13.         iR = cmd.ExecuteNonQuery();  
  14.     }  
  15.     catch { iR = 0; }  
  16.     finally { if (conn.State != 0) conn.Close(); }  
  17.     return iR;  
  18. }  
  19.   
  20. private DataTable ExecuteQuery(string strSql)  
  21. {  
  22.     string sConStr = "Data Source=.\\SQLExpress;Initial Catalog=YourDB;Integrated Security=True";  
  23.     SqlConnection conn = null;  
  24.     DataTable dt = null;  
  25.     try  
  26.     {  
  27.         conn = new SqlConnection(sConStr);                  
  28.         SqlCommand cmd = new SqlCommand(strSql,conn);  
  29.         cmd.CommandType = CommandType.Text;  
  30.         SqlDataAdapter da = new SqlDataAdapter(cmd);  
  31.         conn.Open();  
  32.         dt = new DataTable();  
  33.         //Fill the dataset  
  34.         da.Fill(dt);  
  35.         if (!(dt.Rows.Count > 0)) dt = null;  
  36.     }  
  37.     catch { dt = null;  }  
  38.     finally { if (conn.State != 0) conn.Close(); }  
  39.     return dt;  
  40. }  
  41.   
  42. private PlaceInfo GetPlaceInfoByRow(DataRow dr)  
  43. {  
  44.     PlaceInfo placeInfo = new PlaceInfo();  
  45.     placeInfo.Id = Convert.ToInt32(dr["Id"]);  
  46.     placeInfo.Place = dr["Place"].ToString();  
  47.     placeInfo.About = dr["About"].ToString();  
  48.     placeInfo.City = dr["City"].ToString();  
  49.     placeInfo.State = dr["State"].ToString();  
  50.     placeInfo.Country = dr["Country"].ToString();  
  51.     return placeInfo;  
  52. }  

Section 2

 
Section 2 is the controller code part. Add PlaceInfoController class in Controller folder. Add an attribute on top of class [ApiController], [Route("api/[controller]")]. Also, pass IPlaceInfoService in PlaceInfoController constructors. Create an API method GetPlaceInfos(), GetPlaceInfoById(), PostPlaceInfo(), PutPlaceInfo() & Delete() in PlaceInfoController.The API method returns a response as per the request called by user.
  1. [ApiController]  
  2. [Route("api/[controller]")]  
  3. public class PlaceInfoController : ControllerBase  
  4. {  
  5.     private readonly IPlaceInfoService _placeInfoService;  
  6.     public PlaceInfoController(IPlaceInfoService placeInfoService)  
  7.     {  
  8.         _placeInfoService = placeInfoService;  
  9.     }  
  10.     // GET api/placeinfo  
  11.     [HttpGet]  
  12.     public IEnumerable<PlaceInfo> GetPlaceInfos() =>_placeInfoService.GetAll();  
  13.   
  14.     // GET api/placeinfo/id  
  15.     [HttpGet("{id}", Name = nameof(GetPlaceInfoById))]  
  16.     public IActionResult GetPlaceInfoById(int id)  
  17.     {  
  18.         PlaceInfo placeInfo = _placeInfoService.Find(id);  
  19.         if (placeInfo == null)   
  20.             return NotFound();   
  21.         else   
  22.             return new ObjectResult(placeInfo);  
  23.     }  
  24.   
  25.     // POST api/placeinfo  
  26.     [HttpPost]  
  27.     public IActionResult PostPlaceInfo([FromBody]PlaceInfo placeinfo)  
  28.     {  
  29.         if (placeinfo == nullreturn BadRequest();              
  30.         int retVal=_placeInfoService.Add(placeinfo);              
  31.         if (retVal > 0) return Ok(); else return NotFound();  
  32.     }  
  33.     // PUT api/placeinfo/guid  
  34.     [HttpPut("{id}")]  
  35.     public IActionResult PutPlaceInfo(int id,[FromBody] PlaceInfo placeinfo)  
  36.     {  
  37.         if (placeinfo == null || id != placeinfo.Id) return BadRequest();  
  38.         if (_placeInfoService.Find(id) == nullreturn NotFound();  
  39.         int retVal = _placeInfoService.Update(placeinfo);  
  40.         if (retVal > 0) return Ok(); else return NotFound();              
  41.     }  
  42.   
  43.     // DELETE api/placeinfo/5  
  44.     [HttpDelete("{id}")]  
  45.     public IActionResult Delete(int id)  
  46.     {  
  47.         int retVal=_placeInfoService.Remove(id);  
  48.         if (retVal > 0) return Ok(); else return NotFound();  
  49.     }  
  50. }  

Section 3

 
Section 3 is the Swagger part. For adding Swagger or OpenAPI to an ASP.NET Web API service, you can use Swashbuckle. The NuGet package Swashbuckle.AspNetCore is the library for ASP.NET Core. After you add the NuGet package, you need to add Swagger to the DI container. AddSwaggerGen is an extension method to add swagger services to the collection. To configure Swagger, you invoke the method SwaggerDoc. Passing an Info object, you can define the title, description, contact information, and more in code file Startup.cs.
 
ASP.NET Core 3.1 Web API And Swagger
Next open Startup.cs class and edit function ConfigureServices. Call AddSingleton from services object. Then pass interface IPlaceInfoService and class PlaceInfoService in the method. Next, Add Swagger info object to show small documentation for the API.
 
Next, edit the function Configure and add two method line for Swagger gui interface. These methods are app.UseSwagger() and app.UseSwaggerUi() pass SwaggerEndpoint(service_url,service_name) info. 
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddControllers();  
  4.     services.AddSingleton<IPlaceInfoService, PlaceInfoService>();  
  5.     services.AddSwaggerGen(options =>  
  6.     {  
  7.         options.SwaggerDoc("v2"new Microsoft.OpenApi.Models.OpenApiInfo  
  8.         {  
  9.             Title = "Place Info Service API",  
  10.             Version = "v2",  
  11.             Description = "Sample service for Learner",  
  12.         });  
  13.     });  
  14. }  
  15.   
  16. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  17. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  18. {  
  19.     if (env.IsDevelopment()) app.UseDeveloperExceptionPage();  
  20.     app.UseHttpsRedirection();  
  21.     app.UseRouting();  
  22.     app.UseAuthorization();  
  23.     app.UseEndpoints(endpoints =>{endpoints.MapControllers();});  
  24.     app.UseSwagger();  
  25.     app.UseSwaggerUI(options =>options.SwaggerEndpoint("/swagger/v2/swagger.json""PlaceInfo Services"));  
  26. }  
The extension method UseSwagger adds Swagger middleware and specifies that a JSON schema file should be generated. The default URI that you can configure with UseSwagger is /swagger/{version}/swagger.json. With the document configured in the previous code snippet, the URL is /swagger/v1/swagger.json. The method UseSwaggerUi enables the graphical user interface for Swagger and defines the URL in code file Startup.cs.
 
Finally, the update key launchUrl in launchsettings.json file. Key-value is "swagger", then build and run the Web API project.
  1. {  
  2.   "$schema""http://json.schemastore.org/launchsettings.json",  
  3.   "iisSettings": {  
  4.     "windowsAuthentication"false,  
  5.     "anonymousAuthentication"true,  
  6.     "iisExpress": {  
  7.       "applicationUrl""http://localhost:60696",  
  8.       "sslPort": 44320  
  9.     }  
  10.   },  
  11.   "profiles": {  
  12.     "IIS Express": {  
  13.       "commandName""IISExpress",  
  14.       "launchBrowser"true,  
  15.       "launchUrl""swagger",  
  16.       "environmentVariables": {  
  17.         "ASPNETCORE_ENVIRONMENT""Development"  
  18.       }  
  19.     },  
  20.     "TestWebApi": {  
  21.         "commandName""Project",  
  22.         "launchBrowser"true,  
  23.         "launchUrl""swagger",  
  24.         "applicationUrl""https://localhost:5001;http://localhost:5000",  
  25.         "environmentVariables": {  
  26.             "ASPNETCORE_ENVIRONMENT""Development"  
  27.         }  
  28.     }  
  29.   }  
  30. }  

Output

 
ASP.NET Core 3.1 Web API And Swagger
 

Conclusion

 
This article shows and explains to beginners how to create a Web API in ASP.NET Core and use Swagger. Swagger is a GUI interface to communicate with a Web API. Check a Youtube video of the tutorial to understand more about creating a Web API and using Swagger.