When developing a project, it is always necessary to compile the documentation and keep it up-to-date. This can be achieved in several different ways. In general, the automatic documentation capabilities are always used, which allows you to obtain a good quality of documentation with a minimal time cost, which will always correspond to the current version of your API. Currently, a very popular and functional framework for working with the API is Swagger.
Let's create an ASP.NET Core API application. Later, add a default controller ValuesController.
To use Swagger, you must install the following library.
PM > Install-Package Swashbuckle.AspNetCore
Now, you have to go to the Startup.cs file, go to ConfigureServices, and AddSwaggerGen. The method will look like this.
- public void ConfigureServices(IServiceCollection services) {
- services.AddMvc();
- services.AddSwaggerGen(c => {
- c.SwaggerDoc("v1", new Info {
- Version = "v1",
- Title = "Test API",
- Description = "ASP.NET Core Web API"
- });
- });
- }
After that, add the Swagger UI to the Configure method, after which it will look like this.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- app.UseMvc();
- app.UseSwagger();
- app.UseSwaggerUI(c => {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1");
- });
- }
If I add a new controller, for example, UsersController, and I add methods to work with the user data, these will automatically begin to appear here.
You can see which templates are used in the API, which settings are required, and which ones are not. Here too, you can test the work of your methods. To do this, you must select the desired method and click on "Try it out".
- public class UserDto {
- [JsonIgnore]
- public Guid Id {
- get;
- set;
- }
- [Required]
- public string FirstName {
- get;
- set;
- }
- [Required]
- public string LastName {
- get;
- set;
- }
- [Required]
- [JsonProperty(PropertyName = "mobilePhone")]
- public string Phone {
- get;
- set;
- }
- public string Email {
- get;
- set;
- }
- }
You can see here that you can use various familiar attributes for all, which are well understood and treated in Swagger.
Use in Postman
It is also very convenient to import the JSON, which generates the Swagger in Postman. All you need for a successful import is to insert a link into the JSON file. After that, all the available methods will be available in Postman. The methods for which the description was given will be signed, which further facilitates the use of these methods.
At the moment, Swagger can work with more than 25 programming languages. Its use is, therefore, not limited to .NET Core. It can also be useful in almost any project in which the API is created.