Automating API Client Generation: Improve Your Productivity with GitHub Actions

In software development, continuous integration and continuous delivery (CI/CD) are essential for increasing productivity and minimizing errors. A common challenge is ensuring that API clients (components that consume APIs) are always up-to-date with API changes. Lack of synchronization can lead to failures and inconsistencies in the system. To address this problem, an effective strategy is to automate the generation of API clients whenever a new version of the API is released. This article discusses how you can use GitHub Actions to automatically generate and update API clients, focusing on tools like NSwag and Kiota, to ensure that API clients are always in sync with the latest version of the API.

Objectives

  • Promote greater productivity: Automating API client generation reduces the time developers spend on repetitive tasks, allowing them to focus on more complex activities.
  • Reduce the risk of programming errors: Automation ensures that API clients are consistently generated according to the latest API contracts, reducing integration errors.
  • DTOs update: Keep Data Transfer Objects (DTOs) up-to-date with API evolution, ensuring that the API client and API are always in sync.

Prerequisites

  • API repository hosted on GitHub
  • GitHub Actions configuration
  • Tool for generating API clients (e.g., NSwag, Kiota, Swagger Codegen)

Basic Concepts

OpenAPI (Swagger)

OpenAPI, formerly known as Swagger, is a specification for creating RESTful API interfaces. It allows developers to define the structure of their APIs in a standardized way, facilitating documentation, development, and integration between services.

Benefits of using OpenAPI:

  • Automated Documentation: Automatic generation of detailed API documentation.
  • Interoperability: Facilitates integration with other tools and services.
  • Validation and Testing: Tools for automatic API validation and testing.
  • Client Generation: Ability to generate API clients in various programming languages.

NSwag

NSwag is a popular tool for generating API clients and documentation from OpenAPI specifications. It supports generating clients in C#, TypeScript, and other languages, and allows for customization of the generated clients.

Benefits of NSwag:

  • Support for multiple languages: Generates API clients in various programming languages.
  • Customization: Allows customization of client generation according to your needs.
  • Integration with .NET: Easy integration with .NET projects.

Kiota

Kiota is a Microsoft tool for generating API clients from OpenAPI specifications. It is designed to be highly configurable and extensible, making it easy to integrate with the Microsoft ecosystem.

Benefits of Kiota:

  • Integration with Azure: Great integration with Azure services and other Microsoft tools.
  • High configurability: Allows fine-tuning of API client generation.
  • Support for .NET and TypeScript: Generates API clients for .NET and TypeScript, with support for other languages in the future.

Step-by-Step

1. Swagger Configuration in the API

To automatically generate API clients, your API must provide an OpenAPI (Swagger) specification. Make sure your API is configured to generate the swagger.json file.

public void ConfigureServices(IServiceCollection services) { 
    services.AddSwaggerGen(c => { 
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 
    }); 
}

2. GitHub Actions Configuration

Create a YAML file in your GitHub repository to configure GitHub Actions. This file defines the pipeline that will run whenever a new version of the API is released.

name: Generate API Client
on:
  release:
    types: [published]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout repository
      uses: actions/checkout@v2
    - name: Set up .NET Core
      uses: actions/setup-dotnet@v1
      with:
        dotnet-version: '8.0.x'
    - name: Restore dependencies
      run: dotnet restore
    - name: Build API project
      run: dotnet build --configuration Release
    - name: Generate API client with NSwag
      run: |
        dotnet tool install --global NSwag.ConsoleCore
        export PATH="$PATH:/home/runner/.dotnet/tools"
        nswag openapi2csclient /input:swagger.json /output:Client.cs        
    - name: Generate API client with Kiota
      run: |
        dotnet tool install --global Microsoft.OpenApi.Kiota
        kiota --input swagger.json --language csharp --output ./GeneratedClient        
    - name: Commit and push generated client
      run: |
        git config --global user.name "github-actions[bot]"
        git config --global user.email "github-actions[bot]@users.noreply.github.com"
        git add .
        git commit -m "Update API client"
        git push origin main        

3. Component Project Details

Where the Sources Are Stored

The source files of the generated API client will be stored in a specific directory within the repository, such as ./GeneratedClient for Kiota or in the project root for NSwag.

Creating the Component Project

To organize the API client as a separate project, you can create a library project within your solution. For example, a .NET library project can be created as follows:

dotnet new classlib -o ApiClientLibrary

After generating the API client, move the generated files to the ApiClientLibrary directory.

Package Update

Whenever there is a new API release, the GitHub Actions pipeline will update the API client files and commit these changes to the repository. To facilitate distribution, you can configure the package to be published to a package registry such as NuGet.

Add a step in the pipeline to package and publish the library:

- name: Pack and push to NuGet
  run: |
    dotnet pack ApiClientLibrary/ApiClientLibrary.csproj -c Release -o ./nupkgs
    dotnet nuget push ./nupkgs/*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json    

Customizations

Both NSwag and Kiota allow for advanced customizations. You can add custom configurations to the NSwag configuration file or pass additional parameters to Kiota.

Example of custom configuration for NSwag:

- name: Generate API client with NSwag
  run: |
    dotnet tool install --global NSwag.ConsoleCore
    export PATH="$PATH:/home/runner/.dotnet/tools"
    nswag openapi2csclient /input:swagger.json /output:Client.cs /namespace:MyNamespace    

For Kiota, you can specify additional configurations as needed.

Conclusion

Automating API client generation using GitHub Actions, NSwag, and Kiota is an excellent way to increase team productivity and reduce errors. This approach ensures that API clients are always up-to-date with the latest API changes, providing smoother and more efficient integration.