ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 5 NSwag – Setting up Swagger and Auto generate API client code)

This is the continuation of my previous article ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 4 AutoMapper – Map object properties to another object) In this article we will use NSwag to generate our API client code.

Advertisements

Setting up Swagger

In InvoiceManagementApp.Api install the nuget package NSwag.AspNetCore

Then update Startup.cs file to use Swagger. Add this code in ConfigureServices method of Startup class.

services.AddOpenApiDocument(configure =>
            {
                configure.Title = "InvoiceManagementApp API";
                configure.AddSecurity("JWT", Enumerable.Empty<string>(), new OpenApiSecurityScheme
                {
                    Type = OpenApiSecuritySchemeType.ApiKey,
                    Name = "Authorization",
                    In = OpenApiSecurityApiKeyLocation.Header,
                    Description = "Type into the textbox: Bearer {your JWT token}."
                });

                configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));
            });

Then inside the Configure method of Startup class. Add this code to use Swagger.

app.UseOpenApi();
app.UseSwaggerUi3();
Advertisements

Now run your application and navigate to https://localhost:<change_this_with_your_port>/swagger

You can use this UI to test your Api. Click the Authorize button to add your token.

Then now you can add or get invoices using swagger ui.

Advertisements

Create Base Class for API Client Code

Before we start our configuration to automate API client code generation. We need to create our base class to handle token and base url.

In InvoiceManagementApp.Api open the folder ClientApp. Then add a new folder inside src folder called utils.

inside the utils folder add a new typescript file called apiClientBase.ts

import authService from '../components/api-authorization/AuthorizeService';
export class ApiClientBase {
  baseApiUrl: string = "https://localhost:44335/";
  
  protected async transformOptions(options: RequestInit): Promise<RequestInit> {
    const token = await authService.getAccessToken();
    options.headers = { ...options.headers, authorization: `Bearer ${token}`};
    return Promise.resolve(options);
  }

  protected transformResult(url: string, response: Response, processor: (response: Response) => any) {
    return processor(response);
  }

  protected getBaseUrl(defaultUrl: string, baseUrl?: string) {
    return this.baseApiUrl;
  }
}
Advertisements

Auto Generate API Client Code

Download and install NSwagStudio installer from https://github.com/RicoSuter/NSwag/wiki/NSwagStudio

Open NSwagStudio. Select NetCore31 for Runtime then click the tab OpenAPI/Swagger Specification then input the path of your swagger.json (https://localhost:<change_this_with_your_port>/swagger/v1/swagger.json)

Then check TypeScript Client and click the TypeScript Client tab

  • Change the values of this fields
  • Template: Fetch
  • Base Class: ApiClientBase
  • Check then Use the ‘getBaseUrl(defaultUrl: string)’ method fromthe base class
  • Check the Call ‘transformOptions’ on the base class or extension class
  • Check the Call ‘transformResult’ on the base class or extension class

In Path to class extension code file, click the button with ‘…’ to locate your base class which the file that we did earlier apiClientBase.ts

Then for the output file copy the path in Path to class extension code file then change the apiClientBase.ts to api.ts

Click File then Save as. Save the file in InvoiceManagementApp.Api using the file name nswag.json.

Advertisements

Install NSwag.MSBuild nuget package in InvoiceManagementApp.Api Then right click the InvoiceManagementApp.Api and click the Unload Project.

Then right click to InvoiceManagementApp.Api and click Edit InvoiceManagementApp.Api.csproj

Add this code in InvoiceManagementApp.Api.csproj

<Target Name="NSwag" AfterTargets="Build">
    <Copy SourceFiles="@(ReferencePath)" DestinationFolder="$(OutDir)References" />
    <Exec Command="$(NSwagExe_Core31) run nswag.json /variables:Configuration=$(Configuration),OutDir=$(OutDir)" />
    <RemoveDir Directories="$(OutDir)References" />
  </Target>

Save the file then Reload the InvoiceManagementApp.Api project. Build the project and if everything goes well it should generate a file called api.ts inside the utils folder.

Advertisements

Currently our ClientApp use javascript, but in the next article ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 5 React – How To Convert ReactJs To Typescript) we will convert the ClientApp to use typescript.

SOURCE CODE: https://github.com/alexcalingasan/InvoiceManagementApp/tree/feature/add_nswag

RELATED ARTICLES:

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 1)

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 2 Auditing in EF Core with CreatedBy and LastModifiedBy)

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 3 MediatR and FluentValidation)

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 4 AutoMapper – Map object properties to another object)

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 5 NSwag – Setting up Swagger and Auto generate API client code)

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 6 React – How To Convert ReactJs To Typescript)

ASP.NET Core 3.1 Clean Architecture – Invoice Management App (Part 7 React – Create And List Invoice)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s