API Analyzers, introduced with ASP.Web Core two.two, enable you to adhere to a established of conventions to make improvements to the documentation of the APIs of your ASP.Web Core apps. API Analyzers function with any controller that is adorned with the [ApiController] attribute. This post discusses how we can function with API Analyzers in ASP.Web Core 3.1.
To function with the code illustrations supplied in this post, you need to have Visible Studio 2019 set up in your system. If you never presently have a duplicate, you can download Visible Studio 2019 below.
Develop an ASP.Web Core 3.1 API undertaking
Initial off, let’s make an ASP.Web Core undertaking in Visible Studio. Assuming Visible Studio 2019 is set up in your system, adhere to the techniques outlined under to make a new ASP.Web Core undertaking in Visible Studio.
- Launch the Visible Studio IDE.
- Click on “Create new undertaking.”
- In the “Create new project” window, find “ASP.Web Core Net Application” from the checklist of templates exhibited.
- Click Future.
- In the “Configure your new project” window, specify the title and site for the new undertaking.
- Click Develop.
- In the “Create New ASP.Web Core Net Application” window proven subsequent, find .Web Core as the runtime and ASP.Web Core two.two (or later) from the drop-down checklist at the top rated. I’ll be making use of ASP.Web Core 3.1 below.
- Select “API” as the undertaking template to make a new ASP.Web Core API application.
- Guarantee that the test containers “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be making use of these options below.
- Guarantee that Authentication is established as “No Authentication” as we won’t be making use of authentication both.
- Click Develop.
This will make a new ASP.Web Core API undertaking in Visible Studio. Now find the Controllers resolution folder in the Alternative Explorer window and click “Add -> Controller…” to make a new controller named DefaultController. We’ll use this undertaking in the subsequent sections of this post.
Set up the API Analyzers NuGet package deal
If you are making use of with ASP.Web Core two.two, to function with API Analyzers in ASP.Web Core, you need to install the Microsoft.AspNetCore.Mvc.Api.Analyzers package deal from NuGet. You can do this both by using the NuGet Offer Manager inside the Visible Studio 2019 IDE, or by executing the next command in the NuGet Offer Manager Console:
Set up-Offer Microsoft.AspNetCore.Mvc.Api.Analyzers
Notice that you do not have to have to install the NuGet package deal if you are making use of ASP.Web Core 3. or increased mainly because the analyzers are included as part of the .Web Core 3.x SDK.
Develop the product and repository classes in ASP.Web Core
Select the Models folder of the undertaking we have just produced and make a product course as proven under.
general public course Creator
general public int Id get established
general public string FirstName get established
general public string LastName get established
We’ll also have to have a Repository course – a simple, minimalist implementation of a repository – we’re not connecting to the databases below. The AuthorRepository course is proven in the code snippet given under.
general public course AuthorRepository
Listingauthors = new Listing ()
new Creator
Id = 1,
FirstName = "Joydip",
LastName = "Kanjilal"
,
new Creator
Id = two,
FirstName = "Steve",
LastName = "Smith"
general public async TaskGetAuthor(int id)
var author = authors.FirstOrDefault(a => a.Id == id)
return await Task.FromResult(author)
general public async TaskSaveAuthor(Creator author)
var end result = authors.The place(a => a.Id == author.Id)
if(end result == null)
authors.Incorporate(author)
return await Task.FromResult(true)
return await Task.FromResult(bogus)
The AuthorRepository course is made up of two techniques, particularly GetAuthor and SaveAuthor. The former returns an instance of the Creator course if the author is found in the selection, and the latter is utilized to insert an instance of the Creator course to the selection if the author does not presently exist in the selection. You may possibly ignore the calls to Task.FromResult techniques – these have been utilized only to fulfill the compiler.
Develop the controller course in ASP.Web Core
Future, switch the resource code of the DefaultController course with the next code.
[Route("api/[controller]")]
[ApiController]
general public course DefaultController : ControllerBase
AuthorRepository authorRepository = new AuthorRepository()
[HttpGet("id")]
general public async Task> Get(int id)
if (id <= 0)
return BadRequest()
try
var author = await authorRepository.GetAuthor(id)
if (author == null)
return NotFound()
return Ok(author)
capture
return BadRequest()
[HttpPut]
general public async Task> Put([FromBody] Creator author)
var end result = await authorRepository.GetAuthor(author.Id)
if (end result == null)
return NotFound()
if (author == null)
return BadRequest()
try
var results = await authorRepository.SaveAuthor(author)
if (!results)
return BadRequest()
return Ok(author)
capture
return BadRequest()
We’ll use this controller in the subsequent sections of this post.
Set up and configure Swagger in ASP.Web Core
Future, you need to install Swashbuckle in your undertaking to deliver Swagger files for your ASP.Web Core API. You can do this both by setting up the Swashbuckle.AspNetCore package deal by using the NuGet Offer Manager inside the Visible Studio 2019 IDE, or by executing the next command in the NuGet Offer Manager Console:
Set up-Offer Swashbuckle.AspNetCore
Assuming Swashbuckle.AspNetCore package deal has been set up, compose the next code in the ConfigureServices technique of the Startup course to insert Swagger to the request processing pipeline.
expert services.AddSwaggerGen(c =>
c.SwaggerDoc("v1", new OpenApiInfo Title = "ApiAnalyzersDemo API",
Model = "v1")
)
The AddSwaggerGen extension technique is utilized below to specify the metadata for the API documentation. You need to also specify the Swagger URL and enable the Swagger UI in the Configure technique of the Startup course as proven in the code snippet given under.
application.UseSwagger()
application.UseSwaggerUI(c =>
c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1")
)
Browse the Swagger endpoint for your ASP.Web Core application
So much so very good. When you run the application and search the Swagger endpoint, the documentation for the GET technique need to search like that in Figure 1.
Figure 1.
Notice that the Swagger documentation exhibits only the facts of the Http Position Code 200 that is returned from the technique (if it succeeds) – it does not seize the other status codes that the technique returns. Right here is just the place API Analyzers can aid. You can just take benefit of API Analyzers to take care of this lacking piece of facts in the documentation.
If you’re making use of ASP.Web Core two.two, when you compile the code, you will see the warnings as proven in Figure two.
Figure two.
Select any of the warnings and then press the “Ctrl” and “.” keys jointly to see the potential fixes. You can see that the advisable take care of is to insert the ProducesResponseType attribute as proven in Figure 3.
Figure 3.
Given that we’re making use of ASP.Web Core 3.1 below, you can insert the next characteristics at the top rated of your technique or controller course in get to doc all of the HTTP status codes currently being utilized in the action technique, i.e., 200, four hundred, and 404.
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesDefaultResponseType]
Total ASP.Web Core API Analyzers example
The next code listing exhibits the total code of the DefaultController course for your reference.
[Route("api/[controller]")]
[ApiController]
[ApiConventionType(typeof(DefaultApiConventions))]
general public course DefaultController : ControllerBase
AuthorRepository authorRepository = new AuthorRepository()
[HttpGet("id")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
general public async Task> Get(int id)
if (id <= 0)
return BadRequest()
try
var author = await authorRepository.GetAuthor(id)
if (author == null)
return NotFound()
return Ok(author)
capture
return BadRequest()
[HttpPut]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
general public async Task> Put([FromBody] Creator author)
var end result = await authorRepository.GetAuthor(author.Id)
if (end result == null)
return NotFound()
if (author == null)
return BadRequest()
try
var results = await authorRepository.SaveAuthor(author)
if (!results)
return BadRequest()
return Ok(author)
capture
return BadRequest()
Now run the application again and search to the Swagger URL. Figure four exhibits what the output need to search like.
Figure four.
API Analyzers is a beneficial addition to ASP.Web Core. As we have viewed, you can just take benefit of API Analyzers and Swashbuckle, an open resource undertaking for making Swagger files, to deliver superior API documentation. For the reason that API Analyzers can doc a status code that isn’t returned from an action technique, it tends to make documenting your APIs a lot quicker and less difficult. For API documentation we have utilized Swashbuckle, an open resource undertaking for making Swagger files.
You can find out additional about Swashbuckle from my past post below.
How to do additional in ASP.Web Core:
Copyright © 2020 IDG Communications, Inc.