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.
Prerequisites
Section titled “Prerequisites”Make sure the NightVision CLI is installed: Installing the CLI.
Tutorial
Section titled “Tutorial”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.
- First, clone the example GitHub repository and enter the directory:
git clone https://github.com/nvsecurity/ReplacementsExample.gitcd ReplacementsExample- Run the following command to perform the extraction:
nightvision swagger extract ./ -o openapi-spec.yml -l dotnet --no-upload- Open the generated
openapi-spec.ymlfile. 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- There is a new file in the directory:
nv.config. Notice that the first value in thereplacementsobject is set tonull. That is the value that must be modified to properly resolve the variable.
{ "replacements": { "Microsoft.AspNetCore.Builder.WebApplication.Services.GetRequiredService().Value.ApiPrefix": null }}- Now that we know the variable name, let’s find the value. Open the
appsettings.jsonfile. Observe that thePrefixvalue is set toapi/v2. That is the replacement value that you should set in the nv.config file. - Modify the
nv.configfile to include theapi/v2value instead ofnull:
{ "replacements": { "Microsoft.AspNetCore.Builder.WebApplication.Services.GetRequiredService().Value.ApiPrefix": "api/v2" }}- Now generate a new OpenAPI file by running the NightVision Swagger extraction again:
nightvision swagger extract ./ -o openapi-spec.yml -l dotnet --no-upload- Observe that the
openapi-spec.ymlfile includes the proper variables:
paths: # The proper value is now included in the OpenAPI file. /api/v2: get: x-source: Program.cs~~14