Generate Angular API Service Code Using Swagger

Hello Friends, In this article, we will discuss how to generate an angular API service code using Swagger. The Swagger project provides tools to generate OpenAPI specifications from existing ASP.NET(Core) Web API controllers and client code from these OpenAPI specifications. we will use NSwag Studio to generate TypeScript client services.

Use NSwag in the ASP.NET Core API

Step 1. Add Swashbuckle.AspNetCore package in the project using the following command

Install-Package Swashbuckle.AspNetCore

Step 2. In the Startup.cs file update ConfigureServices() method with below code:

public void ConfigureServices(IServiceCollection services)
{

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "Swagger Demo API",
            Version = "v1",
            Description = "Demo API for swagger code generation",
        });
    });
}

Step 3. Now, in Startup.cs file update Configure() method with below code:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerDemoAPI v1"));
  }
}

Step 4. Run the project and navigate to https://localhost:44361/swagger/index.html URL and it will show your swagger API.

Generate Angular Services with NSwag Studio

Step 1. Create an Angular project using the following command:

ng new SwaggerDemoWeb

Step 2. Download NSwag Studio and install it.

Step 3. Open NSwag Studio and enter the “Specification URL” from the previous step API (e.q. “https://localhost:44361/swagger/v1/swagger.json”). Select “TypeScript Client” as “Outputs”:

Step 4. Select the “Angular” template:

Step 5. Configure api.ts as extension code file in NSwag Studio:

Click on the “Generate Outputs” or “Generate Files” button:

Note: if you want to generate an API service file then click on “Generate Files”.

I hope this article helps you and you will like it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories