Using AutoRest for PowerShell to generate PowerShell Modules

Recently the Beta of the AutoRest for PowerShell Generator has been made available. At the recent Microsoft MVP Summit in Seattle Garrett Serack gave those that were interested a 1 hr corridor session on getting started with AutoRest for PowerShell.

AutoRest is a tool that generates client libraries for accessing RESTful web services. Microsoft are moving towards using AutoRest to generate SDK’s for the API’s in the standard languages they provide SDK’s for. In addition the AutoRest for PowerShell generator aims to automate the generation of PowerShell Modules for Azure API’s.

In this post I’ll give an intro to getting started with AutoRest to generate PowerShell modules using an AutoRest example and then an Azure Function based API.

AutoRest for PowerShell Prerequisites

AutoRest is designed to be cross-platform. As such its dependencies are NodeJS, PowerShell Core and Dotnet Core.

AutoRest for PowerShell Installation

Installation is done via command line once you have NodeJS installed and configured

npm install -g autorest@beta

if you have previously installed AutoRest you will want to update to the latest version as updates and fixes are coming regularly

autorest --reset

AutoRest Update.PNG

Building your first AutoRest for PowerShell Module

The AutoRest documentation has a couple of examples that are worth using initially to get to know the process and the expected output from AutoRest.

From a PowerShell Core command prompt (type pwsh in a command window) make the following Invoke-WebRequest (IWR) to retrieve the XKCD Swagger/OpenAPI file. I pre-created a sub-directory named XKCD under the directory where I ran the following command.

iwr https://raw.githubusercontent.com/Azure/autorest/master/docs/powershell/samples/xkcd/xkcd.yaml -outfile ./xkcd/xkcd.yaml

Download XKCD Yaml.PNG

We can now start the process to generate the PowerShell module. Change directory to the directory where you put the xkcd.yaml file and run the following command.

autorest --powershell --input-file:./xkcd.yaml

AutoRest Generate Libs.PNG

Following a successful run a generated folder will be created. We can now build the PowerShell Module. We can add the -test flag so that at the end of Generating the Module, Pester will be used to test it. First run PowerShell Core pwsh then build-module

pwsh 
./generated/build-module.ps1 -test

AutoRest - Build Module.PNG

With the module built and the tests passed we can run it. We need to load the module and look to see the cmdlets that have been built for the API.

.\generated\run-module.ps1 xkcd.psm1
get-command -module xkcd

AutoRest - Load Module.PNG

Using the Get-ComicForToday cmdlet we can query the XKCD API and get the Comic of the Day.

Get-XkcdComicForToday | fl

AutoRest - Comic of the Day.PNG

Taking it one step further we can download the comic of the day and open it, with this PowerShell one-liner.

invoke-webrequest (Get-XkcdComicForToday).img -outfile image.png ; & ./image.png

Download and Display XKCD Comic of the Day.PNG

Let’s Create a Simple API – BOFH Excuse Generator

I created an HTTP Trigger based PowerShell API Function that takes GET requests and returns a BOFH – Bastard Operator from Hell (warning link has audio) style excuse. For those that haven’t been in the industry for 20+ years or aren’t familiar with the Bastard Operator from Hell, it is essentially a set of (semi) fictional transcripts of user interactions from a Service Desk Operator (from Hells’) perspective set in a University environment. Part the schtick is an Excuse of the Day. My API when queried returns a semi plausible Excuse of the Day.

Here is my HTTP Trigger PowerShell Azure Function (v1). A simple random excuse generator.

I configured the function for anonymous, GET operations only and the route to be excuse

Testing the Function from my local machine showed it was working and returning an excuse.

Now it’s time to generate the OpenAPI Spec. Select the Azure Function App => Platform Features => API definition

Select Generate API definition template and the basics of the OpenAPI spec for the new API will be generated. I then updated it with the output application/json and what the API returns as shown in the highlighted sections below. Select Save

Now we can test it out and we see that we have success.

Taking the OpenAPI Spec (YAML format file) for our BOFH Excuse API we go through the steps to successfully generate the PowerShell Module using AutoRest. Running the freshly baked cmdlet from the BOFH PowerShell Module returns a BOFH Excuse. Awesome.

Summary

Using AutoRest it is possible to generate PowerShell Modules for our API’s. Key to the successful generation is the definition of the OpenAPI Spec for our API. In my example above, obviously if you don’t define what the API call returns then the resulting cmdlet will query the API, but won’t return the result.

Creating Service Contract with AutoRest, Swagger and HAL

According to Richardson Maturity Model, REST API level 3 should provide hypermedia within responses as metadata, so that users can easily navigate to other resources. This is particularly important if Microservices architecture (MSA) is considered for your service or application. Because MSA is a collection of small REST API services, each API server should provide complete set of documents or manuals for others to consume it properly. In order to provide document automation, Swagger is one of the best choices, and HAL, in order to provide hypermedia within the response, is also yet another option. Of course, consuming those REST API at client applications is also important. In this case, AutoRest can give great benefits for your development. In this post, I’ll discuss HAL, Swagger and AutoRest with some demo code.

Integrating HAL

HAL (Hypertext Application Language) has been suggested by Mike Kelly. Its formal specification can be found at this IETF draft. Generally speaking, many REST API services are well structured. They don’t just only return data in the response, but also include various metadata for reference purpose, in their own way. HAL offers a standardised way of including hyperlinks into those responses. Here’s an example

If you send a request with the URL above, the expecting response will look like:

However, if HAL is applied, the response will look like:

Let’s see another example returning a collection.

The request will expect response like:

If HAL is applied, the response will look like:

Can you see differences? HAL applied responses contain much richer data that can easily navigate to other resources.

OK, theory is done. Let’s implement HAL on your API. First of all, assuming you’ve got an existing Web API app containing models of Product and ProductCollection looking like:

There are many HAL implementations on our NuGet. For now, I’m going to use WebApi.Hal. Once installed, you can modify those models with this way, by minimising impacts on the existing application:

Then, register HAL into your Global.asax.cs or Startup.cs:

That’s it! Too simple? Here’s the magic inside the Representation class. It has the public Links property that takes care of all hypertext links. All we need after the HAL implementation is to add appropriate links to each instance, manually or automatically. Here’s a way to include hyperlinks manually within a controller level:

Once it’s done, build it and check the API response. Then you’ll see the result including those HAL links like above. Now, let’s move to the next part, Swagger.

Integrating Swagger

According to Swagger website, Swagger provides a standard, language-independent interface to REST API so that both humans and computers can easily find and understand the API structure without reading source codes or documents. There are several other alternatives like RAML or API Blueprint, so it’s up to you which one should you choose.

Swashbuckle is one of C# implementations of Swagger. It’s easy to use and virtually zero configuration is required for the basic usage. Let’s install Swashbuckle into your project. Once installed, it also adds another file, SwaggerConfig.cs under the App_Start directory. You can directly use it or do some modification for your application. Let’s have a look.

When you open SwaggerConfig.cs file, it looks like above. In order for you to have more control on it, comment out the first line, [assembly: ...] and make the Register() method to be an extension method:

Then, put the following like into either your Global.asax.cs or Startup.cs for registration:

That’s all. Build and run your app, type URL like http://my.api.service/swagger and you will see the Swagger UI screen like:

What you need to notice is the JSON schema URL in the picture above. When you type the URL from Postman, it will look like:

This is basically a JSON schema file and pretty much equivalent to WSDL from SOAP. With terms of WCF, it contains both service contract and data contract so, with this schema, your client applications can access to the API and consume it. There’s no obstacle for it.

So far, we’ve implemented both HAL and Swagger on your REST API server. How can we then consume those APIs on your clients like web app or mobile app? Let’s move onto the next section for this.

Deserialising Swagger JSON schema with AutoRest

Once Swagger JSON schema is generated, your client apps should be able to consume it with minimised efforts. AutoRest can bring great benefits to your client apps. It automatically generates both service contracts and data contracts pointing to your REST APIs using Swagger JSON schema. Currently, AutoRest supports C#, Java, Node.js and Ruby and the number of languages gets gradually expanded.

Here’s an ASP.NET MVC app. Within the app, assuming there’s a folder, Proxies. Swagger JSON schema file is then placed into that folder with name of swagger.json. Then install AutoRest CLI app and runtime library from NuGet. In order to auto-generate client libraries, try the following command on your Command Prompt:

What does the command line mean? Here’s the brief explanation:

  1. Run AutoRest.exe
  2. Input JSON schema name is swagger.json
  3. The namespace for auto-generated files is HalSwaggerSample.WebApp.Proxies
  4. Store auto-generated files into Proxies
  5. Set output file type as C#

After the generation, you will be able to see bunch of files have been stored into the Proxies folder. The most important file is HalSwaggerSampleHalApiApp.cs. Of course, the file name (or class name) will be different from yours. It provides the service endpoint and service contract information. It also contains the corresponding interface, IHalSwaggerSampleHalApiApp, so this service contract is testable, mockable and injectable. Therefore, your controller/action can be written like:

Therefore, the result screen will look like:

Did you find that can’t be easier?

We’ve so far had a look at HAL, Swagger and AutoRest. Both HAL and Swagger are to design your REST API to be more discoverable, readable and maintainable and make client apps build their access point much easier with tools like AutoRest. How about implementing those into your Web API, if you’re considering MSA? Kloud can help you.

The entire sample source code that I wrote for this post can be found at here.

Follow Us!

Kloud Solutions Blog - Follow Us!