DEV Community

Geert van der Cruijsen for Xebia Microsoft Services

Posted on • Originally published at fullcycledeveloper.com on

Generating sandbox APIs for your ASP.Net Core Web APIs

When building APIs I often want to share my contract as soon as possible. Especially when you know your consumers and are you’re open for feedback and discussion on the contract of the API.

Contract first or Code first?

Although I want to share my contract as soon as possible I don’t like these API contract designer tools. My approach is often just creating an empty API in Asp.Net Core by defining the controllers and classes that define the contract. Adding Swashbuckle to your project will generate a Swagger file / Open API Spec based on the controllers and classes that you can use to document your API.

Giving your consumers a testable solution as soon as possible

So an early API specification / contract is quite easy to create. But what if what if we could actually generate a working API from this specification that returns fake data? There are certain tools that can do this for you like Open API Mock. This tool can generate a working API from an API specification and return fake data based on additional extension properties in the specification.

Let’s take a look at a basic swagger file (weather forecast from the built in template when you create a new Asp.Net Core Web API Project). I’ve added some extension properties (x-faker) to the specification by hand so Open API Mock knows what kind of fake data it should generate. Open API Mock generates this data through a library called Faker. It has a wide range of fake data generators from numbers, to street names, phone numbers, bank details etc. Also available in many country specific variants.

"schemas": {
"WeatherForecast": {
"type": "object",
"properties": {
"date": {
"type": "string",
"format": "date-time",
"x-faker": "date.recent"
},
"temperatureC": {
"type": "integer",
"format": "int32",
"x-faker": "datatype.number(-10,35)"
},
"temperatureF": {
"type": "integer",
"format": "int32",
"readOnly": true,
"x-faker": "datatype.number(105)"
},
"summary": {
"type": "string",
"nullable": true,
"x-faker": "lorem.paragraph"
}
},
"additionalProperties": false
}
}

Enter fullscreen mode Exit fullscreen mode

We can now use this swagger file and feed it to Open API Mock to generate a working API by using Docker to run the Open API Mock container.

docker run -v "[path to your]swagger.json:/app/schema.json" -p "8080:5000" jormaechea/open-api-mocker

Enter fullscreen mode Exit fullscreen mode

Now when we test this API you’ll see that Open API Mock returns fake data specified in the faker extension properties of the specification.

[
{
"date":"2022-01-05T22:25:30.366Z",
"temperatureC":-6,
"temperatureF":41,
"summary":"Praesentium iste natus temporibus omnis nihil perspiciatis quo. Rerum odit blanditiis quia autem et earum magnam quod. Suscipit voluptate quia voluptatibus ea reiciendis. Sed praesentium sed in est."
}
]

Enter fullscreen mode Exit fullscreen mode

Adding this functionality automatically to your Swashbuckle generated swagger file

So manually adding a swagger file is nice but what if you want to add this functionality automatically to your swagger file when it’s being generated by Swashbuckle? I’ve created a small extension to Swashbuckle, published through Nuget called Swashbuckle.AspNetCore.ExtensionProperties. What this allows you to do is to add attributes to your classes that are used in the Open API Specification that is generated by Swashbuckle.

If you install the Nuget package you can add attributes in the following way:

public class WeatherForecast
{
 [Faker(fakerValue:"date.recent")]
public DateTime Date { get; set; }

 [Faker(fakerValue:"datatype.number(-10,35)")]
public int TemperatureC { get; set; }

 [Faker(fakerValue:"datatype.number(105)")]
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

 [Faker(fakerValue:"lorem.paragraph")]
public string? Summary { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

Generating the specification file by running the API will result in the exact same json as mentioned earlier in this post.

The source of this nuget package is open source and can be found on my Github repo. It can also be used to add other types of extension properties that you might want to add to your specification file for other tools that process your swagger files.

So whenever we would start a new API Project we could have a running sandbox solution that returns fake data for our API in only a few minutes by just following the following steps mentioned earlier:

  1. Create a new Asp.Net Core Web API Project with Controllers + Classes
  2. Add Swashbuckle to the project
  3. Add the Swashbuckle.AspNetCore.ExtensionProperties NuGet package to the project
  4. Add Faker attributes to your properties in your Classes.
  5. Extract the .json file from your API by running the API and browsing to the Swagger UI on [api]/swagger/
  6. Run the Open API Mock using your swagger file

Using this in Automation / pipelines and automatically posting it to Azure API Management

The steps above are quite easy to do but I always try to set up all deployments through continous delivery pipelines. So what I like to do for every change made to the API is to automatically deploy it’s specification to Azure API Management. There is quite some information on how to do this either by infrastructure as code tech such as ARM or TerraForm but also using the Azure CLI or Powershell. I’ll skip on the basics of how to import an API to API management but would like to focus on how you could work with both a sandbox and the actual API.

Blogs & documentation on Azure API Management deployments from delivery pipelines.

Sandboxes in Azure API Management.

Azure API management has the notion of “Products”. These products are a way you can group certain APIs together and give a specific audience access to these APIs. When working with sandboxes I always prefer to create 2 products, one for the sandbox APIs and one for the actual APIs. This way you have 2 APIs for each of your API. 1 sandbox API in the sandbox product and 1 actual API in the production product.

Sandboxes are APIs that do not contain any real data so opening them up for everyone is a best practice so people can get inspired by browsing through the API list and playing around with them.

How to easily get the Open API Specification from a ASP.Net Core Web API project in a pipeline

The Swashbuckle project comes with a CLI tool to download the Open API specification file with a simple command. You can download and use the Swashbuckle.AspNetCore.Cli tool by running the following command:

dotnet tool install -g --version 6.2.3 Swashbuckle.AspNetCore.Cli
swagger tofile --output swagger.json YourApi/bin/Debug/net6.0/YourApi.dll "v1"

Enter fullscreen mode Exit fullscreen mode

After extracting the Open API Specification file you can now pass it into the Open API Mock container and spin that container up somewhere in the cloud on for example an Azure Container Instance, an Azure Web App for Containers or an AKS cluster if you are already using those. After that hook up the Azure API Management backend to your mock and you’re ready to go.

Conclusion

Hopefully this post, the nuget package and other tools I mentioned helps in shifting left the communication of API designs with your consumers so they have an early view on the contract but also an actual working API sandbox.

Geert van der Cruijsen

Top comments (0)