Skip to content

Handling Unresolved Variables

Sometimes, NightVision’s API Discovery may not be able to resolve certain variables in your code to generate the most accurate OpenAPI spec. For example, an API prefix (such as including the /api/v1 before all API paths) may be read from an environment variable without a default value. In this case, an nv.config file is generated that can help users quickly tweak the generated OpenAPI file for maximum accuracy.

Make sure the NightVision CLI is installed: Installing the CLI.

In this tutorial, you’ll learn how to tweak the nv.config file that was generated by nightvision swagger extract to create the most accurate OpenAPI definition.

  1. First, clone the example GitHub repository and enter the directory:
Terminal window
git clone https://github.com/nvsecurity/ReplacementsExample.git
cd ReplacementsExample
  1. Run the following command to perform the extraction:
Terminal window
nightvision swagger extract ./ -o openapi-spec.yml -l dotnet --no-upload
  1. Open the generated openapi-spec.yml file. You’ll notice that there is an unresolved variable in the URL path - ApiPrefix. A trimmed version of the file is shown below for brevity:
paths:
# Notice how the unresolved variable is included in the path.
# It should be `/api/v2`, based on the appsettings.json file.
/ApiPrefix:
get:
# The x-source value tells you where the endpoint was declared.
# Start looking from here to investigate where the unresolved variable
# originates from.
# If you dig into this file, you'll notice that it uses a convention in
# .NET that pulls the value from the appsettings.json file.
x-source: Program.cs~~14
  1. There is a new file in the directory: nv.config. Notice that the first value in the replacements object is set to null. That is the value that must be modified to properly resolve the variable.
{
"replacements": {
"Microsoft.AspNetCore.Builder.WebApplication.Services.GetRequiredService().Value.ApiPrefix": null
}
}
  1. Now that we know the variable name, let’s find the value. Open the appsettings.json file. Observe that the Prefix value is set to api/v2. That is the replacement value that you should set in the nv.config file.
  2. Modify the nv.config file to include the api/v2 value instead of null:
{
"replacements": {
"Microsoft.AspNetCore.Builder.WebApplication.Services.GetRequiredService().Value.ApiPrefix": "api/v2"
}
}
  1. Now generate a new OpenAPI file by running the NightVision Swagger extraction again:
nightvision swagger extract ./ -o openapi-spec.yml -l dotnet --no-upload
  1. Observe that the openapi-spec.yml file includes the proper variables:
paths:
# The proper value is now included in the OpenAPI file.
/api/v2:
get:
x-source: Program.cs~~14