Api Management

Code first

Code first as the preferred way to manage service contracts (OAS)

Overview

The code-first approach is the preferred way to manage service contracts (OAS), ensuring that the OpenAPI Specification (OAS) is purely generated from C# code. This approach enforces consistency by integrating an automated validation step within the CI/CD pipeline, ensuring the contract remains up-to-date at all times.

OAS generation is performed during the service build process using the Swashbuckle tool.

OAS Generation Process

The service build process is responsible for generating the OAS contract. This is achieved by executing a build step defined in the Eit.Api.csproj project file:

<Exec Command="swagger tofile --yaml --output $(ProjectDirectory)../../contract/contract.yaml $(TargetPath) v1"
      EnvironmentVariables="ASPNETCORE_ENVIRONMENT=SwaggerGen" />

During this step, the service is started with the SwaggerGen environment to produce the OAS file. This ensures that the latest API definition is always available and correctly reflects the service implementation.

Tooling

To enable OAS generation, it is necessary to install the Swashbuckle CLI as a global .NET tool:

dotnet tool install --global Swashbuckle.AspNetCore.Cli --version 6.7.0

This tool is essential for executing the swagger tofile command and generating the OAS contract in YAML format.

Implementation guidelines

The service contract is entirely defined within the presentation layer of the service. Specific DTO classes are used to define the contract, ensuring that only explicitly defined structures are exposed via the API.

Key implementation guidelines:

  • Use C# attributes on classes, methods, and properties to control the generated OAS documentation.
  • DTOs should be carefully designed to represent the intended API contract without exposing unnecessary internal logic.
  • Refer to the provided service templates or existing implementations as a reference.

Example Usage

An example of service implementation following this approach can be found here:

TodoItemsController.cs – Service Example

This example demonstrates how attributes and conventions are applied to ensure accurate API contract generation.

Benefits

By adopting the code-first approach, developers benefit from:

  • Automated contract generation, ensuring accuracy and reducing manual effort.
  • Consistency enforcement, as pipeline checks prevent contract drift.
  • Seamless API evolution, with version-controlled updates.

Copyright © 2025. All rights reserved.