Hi folks. I’ve been tinkering recently with Functions and API Management in Azure, looking at ways to quickly create and monetise APIs, and thought I should share my findings here in case it helps anyone looking to implement a charging model for developers that consume their APIs in Azure. I’ve set it out as a lab so you can follow along, with the aim of tying together several different services into a workable solution to get you started with creating and managing APIs natively with Azure, as well as integrating with Stripe, a third-party payment platform.

This post covers two key services in Azure: Functions and API Management. Azure Functions is a platform that enables developers to execute their code without having to create/manage a server or even a container for it to run in – Azure handles all of the nitty gritty, and you simply define a trigger that kicks off your code (i.e. a HTTP request in the case of an API), and it spins up, does its thing, then spins down, with the ability for each instance to run in parallel. This is complemented nicely by API Management, which you can think of as a front-end gateway that sits over the top of your APIs, protects the back-end, and allows you to do things like require a subscription key to be passed into it for developers to access certain APIs – making it perfect for creating a monetisation solution. Find out more about Azure Functions here and API Management here.

So where do we start? Well, let’s kick things off by creating a Function that will serve as our API.

Creating an Azure Function

There are quite a few ways of doing this, and it all depends on what your preferences are in terms of the language and IDE you want to use. I prefer Visual Studio because I’m lazy and it has a lot of handy templates and debugging for Azure services built in, but the Functions SDK is available in many languages and frameworks, so go ahead and use what you’re comfortable with. There are some handy quickstarts for different languages and methods here, including how to create one in the Azure portal. So I’m going to create a very basic HTTP-triggered Function that will serve an image of a car from Azure Blob storage based on the car registration and angle of the car requested. I’ll then also add some optional parameters for the height and width of the image to be returned in case the developer needs it in a certain size. Why, you ask? I like cars.

Step 1 – Getting Visual Studio set up (skip if you’re using a different IDE)

First thing’s first, after opening up Visual Studio 2017, if you’re doing it my way you need to install the Azure Development tools (if you haven’t previously). You can do this by opening up the Visual Studio installer and checking the Azure Development box (see here for instructions).

Azure development tools

Once you’ve installed this, you’ll have everything you need to develop Functions locally as well as debug them before we even put anything in Azure.

Step 2 – Create the function using a template

One of the quickest ways to create a function is to use a template, so create a new project, then if you want to use C# like me, click on Visual C# then Azure Functions for your template like so:

Create function

Name it whatever you like and click OK. This will create a Functions app, which you can think of as a wrapper for your individual functions. For example, if we wanted to create a serverless app that consisted off a few functions tied together, like one to get a car image based on a trigger, and one to resize it after it’s fetched, we could have these as separate functions within one Function app. For simplicity’s sake, I’ll just do all of this in one function for now, but in building bigger apps, it’s good practice to separate out each action into separate microservices for redundancy, which I plan to cover in more detail in a later article concerning modern app dev design patterns. So to create our function in our new Functions app, right click the C# project in the Solution Explorer pane and click Add then New Azure Function:

new azfunction

Then name it whatever you like – I’ll call mine GetCarImage (so I can remember what it does). Once you’ve done that it will create a new CS file with an empty class, which we can fill with the code we want to execute. Here’s mine (with the blob account credentials removed):

Feel free to copy it if you haven’t got any other test code in mind to write – just bear in mind you’ll need a storage account set up in Azure and a blob storage container within it for each car (named after the registration number, i.e. “AB42 ABC”), with different angles as the image names for the different views of the car, followed by .jpg as the file extensions (i.e. “front.jpg”, “left-side.jpg”). Once you’ve done that, copy over the storage account key and place it where I’ve removed mine in the code. If you’re not familiar with blob storage in Azure yet but still want to give this code a go, this should get you started.

Step 3 – Test the Function locally

As part of the Azure Development tools for Visual Studio, we have a local debugger included, which is very handy for doing testing before we deploy to Azure. Click on the Play button on the top toolbar to test our solution:

 

Function debugger

The command line utility will fire up and announce that it’s listening on a local port on your machine for HTTP requests, and it even handily shows you what parameters we need to pass it in the URL. Let’s test it using my favourite API development software, Postman (available here). Copy the URL from the command line and paste it into a new Postman HTTP request, and then replace the {CarReg} parameter with a container name you created, and {ImageAngle} with one of the image names (without the “.jpg” extension), like so:

Postman test

Note: the red scribble is a real reg number, hence why it’s scribbled out. As you can see, Postman sends off the request to our local Function and it retrieves the image from blob storage, and sends it back to us. Beautiful. Now how do we get this off of our machine and on to Azure?

Step 4 – Publishing to Azure

Go back to visual studio and right-click the C# project in the Solution Explorer and click Publish… Another nice benefit of Visual Studio is that we can publish things directly into our Azure subscription, without having to touch the portal or even leave the IDE. Click on Create new profile to create a new publishing profile, then click Azure function App and Create New, then click Publish. You’ll be prompted to sign in to your Azure subscription during the process if you’re not signed in already.

publish

You’ll then be taken to the Create App Service screen where you need to name your app, pick a subscription where you want it to be deployed, create a Resource Group or pick an existing for it to reside in, and finally create or pick an existing App Service Plan to put it in (which is essentially the hosting plan where you define the performance levels you want and how you want to be billed).

Note: if you have signed up for a free Azure subscription within the past year and qualified for the 1 year’s free usage of select services, Functions is one of these. However, make sure you check your billing set up to ensure you won’t be charged if you’re not expecting to be.

Here’s an example of mine:

Publish app settings

When you’re done click Create. Then, once your publish profile has been populated, you’ll see this screen:

Publish profile

You can see that our App Name has been prepended to azurewebsites.net to form the endpoint that the Functions HTTP trigger will listen to. Now all that’s left to do is click Publish and let Visual Studio do the rest. You can view progress of the deployment in the Output console, and as soon as you see ‘Publish Succeeded’ we’re ready to test the live Function.

Step 5 – Testing the live Function

Now all we need to do is grab a function code that will authorise our Function requests. We can do this by heading to portal.azure.com and navigating to Function Apps (most easily by typing it in the search bar at the top), and finding the app you’ve just deployed in the list:

Function Apps

Click it, and then click the Function name on the left-hand side, denoted by the icon. Then on the right click Get Function URL and you’ll see the auth code appended to the app’s URL which we can copy to our clipboard:

Function URL

Paste this into Postman, and just like before, replace the parameters with a Car Reg and Angle mapped to the image containers and files you created in blob storage. Hopefully, you’ll see the Function is working just like it did locally:

Live test

And we can even specify in the body of our request that we want a smaller image, let’s say 250 x 300 pixels. Change the request type to POST and add a “Content-Type” header of “application/json”, then add the below to the body: { "height": "250", "width":"300" } And you should get the below back after hitting Send:

Live test smaller

So we now have our simple Function. We haven’t had to mess with any servers or containers, we’ve just written some code and deployed it, and it works, which is nice – but how do we take this and turn it into a fully-fledged API, and more important, one we can monetise? That’s where API Management comes in.

Turning our Function into an API

Step 1 – Create our Azure API Management instance

Simply head to portal.azure.com, click Create a resource, and search for API Management. Once you’ve clicked Create on that you’ll need to fill out the name etc. and pick your plan. Stick with Developer tier for now as we won’t be scaling this to 1000s of customers just yet… Give it a few minutes to deploy, which I find always goes slower when you watch the deployment icon in the portal. So, as always, my advice is to get a cup of tea as I’m about to do (preferably in a Storm Trooper mug or something of equivalent nerdiness).

mug

You’ll find it takes a while to fully activate, but we do get access to the dashboard after a few minutes to start tinkering.

Step 2 – Create a Product

While we wait for it to fully activate, we can create a Product. Think of this as the shiny wrapping we’ll put around one or more of our APIs so we can sell it. Essentially the Products are what the developers who’ll consume our APIs will subscribe to. This is especially important when we’re going to charge for subscriptions to our APIs, so we need to create a Product that we’ll do this with. Click Products on the left-hand side menu, and then the Add button at the top, and fill it out like so:

Create an APIM product

As we haven’t yet imported our API, don’t click Select API just yet. Also, in State, change this to Published for testing purposes later on (it’s very easy to un-publish an API so it’s no longer externally visible). Now click Create.

Step 3 – Import our Function as an API

Before we can bring in our Function, we’ll need to give it an Open API definition. This is essentially some metadata that provides information about our API and allows it to be consumed by various services. We can do that by heading back to our Functions App in the Azure portal, clicking on it in the left-hand menu pane and then clicking the Platform features tab:

Platform features

Then click API definition under the API heading, and then switch it over from External URL to Function (preview), and click Generate API definition, which will bring up this view:

Swagger API definition

As if by magic, we now have an automatically populated Swagger Open API definition file that will be associated with the Function, which will inform API Management what our API does and what parameters etc. it requires. Hit Save, then head over to API Management again. Hopefully your instance is now fully deployed, otherwise it may be time for another cup of tea. Head over to APIs on the left-hand menu when it is, then click APIs then select Functions App:

APIM functions app import

This will bring up the menu that allows you to import your Function app. Select Browse and find your Function app, then fill in the other details like its name and description however you like. Make sure at the bottom you select the Product we created, which will add this API to it:

Import function

Click the Create button and your API should be imported into API Management.

Step 4 – Test the API

Okay, so now we want to test our API. To do that however, as of the time of writing, we’ll need to remove the Function’s authorization code for it to now work with API Management. If you head into the APIs tab, click on your new API in the list, and then select the Test tab, you’ll find a dashboard to test responses from your API.

APIM Test

Enter a valid value for CarReg and ImageAngle and click Send and you’ll find that you get a 401 Unauthorized response. That’s because when API Management is passing the request through to your Function in the backend, Functions is expecting an authorization code to be added to the end of the URL (like we did when we tested the Function before). Don’t worry, we can remedy this.

Go to Function Apps in the Azure portal and click on your Function App’s name, then copy the URL:

Function app URL

Paste it into a new tab but put “scm.” just before “azurewebsites.net” before you press enter so it looks like this: “https://myfunctionappname.scm.azurewebsites.net”. This will open up the Kudu console for the webapp your Function is hosted on, which is a powerful configuration tool for editing certain settings and files in your app. We’ll use it to remove the authorization requirement for our Function.

Once it loads up, click Debug Console from the top menu and select CMD from the dropdown. That will take you into a file explorer showing the root folder on your app server, as well as giving you a Command Prompt environment.

Kudu

In the folders/files listed, navigate into site wwwroot {your function app name} and then click on the pencil icon next to function.json. This will bring up an editor to allow you to modify the file. Change the value in “authLevel” from “function” to “anonymous”:

functionjson

Then hit Save. This will allow our requests mediated by API Management to now go through, which you can test by going back to the API Management blade in the portal and sending the test request again in the Test tab:

200 ok response

If all’s well, you should get a 200 OK response back, along with some absolute nonsense in black, red and blue colours. Don’t worry, that’s an image but API Management’s test window can’t display them. If you try using these values in Postman you should see everything working nicely (don’t forget to include the headers that API Management is adding however). We’re now ready to make some dollar.

Note: This serves our purposes for this exercise, but I definitely wouldn’t recommend doing this for a production API as it leaves your Function backend open for external access without going through APIM. There are good ways to address this such as mutual certificates and Virtual Network integration which fall outside the scope for this post – see the docs for more info.

Monetising your new API with Stripe

There are lots of payment platform providers (try saying that phrase 6 times) out there that you can use for this. I’m picking Stripe for this post as it’s very popular and has a good RESTful API service for developers to use along with good documentation, which is certainly hard to come by. What we’re going to do now is match up our Product in API Management to a Stripe Plan, as they equate to similar concepts, which we’ll do using the Plan’s unique ID. Then we’ll use the API Management API (the irony) to query our customers’ usage of our Product in a given period and send that over to Stripe to automate the payments. Sounds simple really…

Step 1 – Create a Stripe Plan

What you need to do first is set up an account with Stripe at https://stripe.com/. Don’t worry, you don’t actually have to set up any payment details etc. to start testing with it, so it’s perfect for our purposes, and you only add these when you’re ready to start taking real payments.

Once you’ve done that, let’s set up a Plan. This will be set to bill at a monthly interval, which will form the basis for a monthly subscription to our API Product.

To make this as easy as possible, I’m going to use Curl. If you’ve not used it before, you can install it here, or using a package manager like APT or Yum in Linux distros, Homebrew in MacOS or Chocolatey for Windows. Basically, Curl will enable us to interact easily with the Stripe API using a Command-Line Interface and create a plan with one command.

Once you’re ready, use the following code in your terminal (with Curl installed) and change the “product[name]” to whatever you want your Product to be called (I advise keeping it the same as Display Name for your APIM Product). You must also change the “id” parameter to be IDENTICAL to the ID of your APIM Product for our code to work later on. This will set the ID for your Stripe Product’s pricing plan. Finally, specify the amount you want charge (I’m charging a very premium 10 pence as it expects integers, so 100 is equivalent to £1):

curl https://api.stripe.com/v1/plans -u sk_test_8QpYJV1qxu0Qbw4HuhJIr4hw: -d product[name]="Griff365 Premium" -d product[type]="service" -d currency=gbp -d interval=month -d id="griff365premium" -d amount=10

Note: if you’re using Curl in PowerShell, don’t forget to include the cmd /c before the code snippet.

You should get an output similar to the below if successful:

Create plan

Now we have a Stripe plan and product directly mapped to our equivalent API Management Product.

Step 2 – Apply a quota policy in API Management

Okay, next thing we need to do is apply some policies to our API. API Management allows us to set up custom policies that can restrict the ways that developers interact with our APIs. For us to set up a monthly subscription, we’ll probably want to add a quota to only allow the developer to make a certain amount of requests in a given month. This will allow us to charge them even more money in future with a Super Premium package that allows a bigger quota. Good capitalist thinking.

We can also do other useful things with policies like adding or removing certain headers and body content on inbound and outbound requests to protect certain information like the backend URL of our API. Check out the documentation here for a good step-by-step guide.

Go into the API Management portal blade and head to the Products pane, and then select the Product you linked to the API we made. Then click Policies. This will allow you to add policies at the Product level that governs all the APIs associated with it. Click your cursor just after “<Inbound>” in the XML file, and then insert the below:

<quota calls="10000" bandwidth="40000" renewal-period="2628000"></quota>

This will allow 10000 requests to the Product’s APIs per developer’s subscription, and it will replenish every month (2,628,000 seconds to be exact). It should look like the below:

Product policy subscription quota

As you can see along the right-hand side, there are many other things you can insert, such as a rate-limit, which will prevent users from spamming your API with too many requests in a short period of time, preventing potential downtime if your backend has a concurrent requests limit. Feel free to have a play and then continue on to the next step when you’re ready.

Step 3 – set up  APIM Delegation to manage user sign up for our Product

Now that we’ve laid the ground-work, we actually have to sign users up to our Stripe Plan when they register for our API Product in the Developer Portal for API Management. This is made possible through something called Delegation, which enables us to tell API Management that we want to manage the sign-up/sign-in and Product subscription processes instead of using the built-in framework. Then we can write some custom code to do this and make the appropriate calls to the Stripe API to sign the user up to our Plan.

In keeping with our Function, I’ll continue with C# and implement our code as a .NET MVC Webapp for this example; however feel free to use whatever you like here. Stripe has great documentation for many different code bases which you can find here.

Before we get started with our code, we need to set up some pre-requisites first. Complete the following steps:

  1. Enable Delegation in the APIM portal by clicking it in the left-hand menu, then ticking both Delegate sign-in & sign-up and Delegate product subscription.
    • Set a URL for your website – for now, we’re going to set this to our local machine for testing. Set this to http://localhost:22245/ which should be the port that Visual Studio uses when we test later on.
    • Generate a Delegation validation key and copy it somewhere safe, you’ll need this later.
    • Click Save.
  2. Go to ‘Management API’ on the left-hand menu and click Enable API Management REST API, then grab the Identifier and Primary Key from the window and put them somewhere safe for later reference.

Once you’ve done both of those things, we’re ready to set up our code.

Step 4 – Create our custom code to manage dev accounts

Now, depending on your code language preference and whether or not you want to build your app from scratch, or are building in this functionality to one of your existing websites, it’s up to you what you do here. I’ve forked some sample code for APIM and edited it so we can use this for our purposes; however if you want to go it alone and build one from the ground-up you’ll need to follow this guide first, and also this documentation for working with the APIM Management REST API, then reconvene at the next step.

Anyway, if you’re using the sample, let’s go ahead. Head to my GitHub repo here: https://github.com/jjgriff93/api-management-samples and clone the code locally so you can work with it. Then head into the “delegation” folder, then “ContosoWebApplication” and open up “ContosoWebApplication.sln” in Visual Studio. This app follows the ASP.NET MVC framework – if you’re not familiar with MVC there’s some handy info here.

Open up “Controllers” in the Solution Explorer and open “AccountController.cs”, which is the Controller of our Webapp that handles all of the incoming HTTP requests from the API Management Developer Portal, routes the user to sign in/sign up in our custom View pages, then redirects them back. You can see how this redirection works by looking at the Delegate() method, which is listening for HTTP GET requests from APIM, and routing them depending on the operation parameter in the request. So that this works with your APIM instance, we need to fill out some values from the previous step.

First, add your Management API details that we collected earlier into line 27-29:

Fill out your values

And then scroll down to line 35 and paste in your Delegation key that you saved earlier:

Delegation key

And finally, paste in your Developer Portal URL into line 39, which you can find by visiting the Overview pane of the APIM portal:

Developer portal access

You should now be ready to test. Press the Start button to build and run the project, and if there are no build errors (check the Output console) then Visual Studio should open up your web browser and run the website from a port on your local machine (If that’s different to 22245 then make sure you go over to the API Management portal and change the port number in http://localhost:22245/ to the one that Visual Studio has assigned to your app, and then hit Save to update APIM – wait a few moments for the changes to go through).

Once your website has loaded up, leave it running and test the Delegation is working by going to the Developer portal URL (the one you pasted into your code a moment ago). This should load up your Developer portal (you can fully customise the look and feel of this portal later). Click Sign in at the top right:

developer portal sign in

This should hopefully redirect us to the website we’re running on our local machine:

Delegation sign in

Follow the Register process and you should find that you can create an account and then be redirected back to the Developer portal, all logged in and ready to go. Nice.

Step 5 – Set up Stripe to create users and delegate product sign up

Now comes the payment stuff (*rubs hands together*). First thing we need to do is use the Stripe API to create a customer in Stripe at the point when a developer signs up in our website. If you stay in the AccountController.cs code and scroll down to line 150, you’ll see where I’ve implemented this:

I’ve added a using Stripe statement at the start of the file and added the NuGet Stripe package so that we can use Stripe’s framework. Then, as you can see in the code above, I’m using a Stripe API key to authenticate and setting the email of the customer to what they inputted into our form (which the Register POST method is ingesting), and then I’m creating a customer object from a call to the Stripe API, which returns us a unique customer ID. Finally, I’m saving this as a StripeId attribute in our local user database for future reference.

If you want to do all of this in a different language/framework, see Stripe’s API reference for creating a customer, which has all the example code you need to implement this.

All you need to do to enable this is add your secret key from Stripe into our code. Head to https://dashboard.stripe.com/account/apikeys and click Reveal test key token next to secret key, and copy this. Then navigate to our code in Visual Studio and paste it into line 44:

Stripe API key

Now run the code again and repeat the previous steps to Register in the Developer Portal (do it in a fresh InPrivate/Incognito/Private Browsing window). Once you’ve done that head over to the Stripe Dashboard and click the Customers tab (https://dashboard.stripe.com/test/customers) and you should hopefully see the email address you entered appear as a customer:

Stripe customers

Magic. You can also see the unique customer IDs that have been assigned by Stripe, which we saved in the code to our local user store along with their name and email address. This is how we can sign the customer up for subscriptions, so if you’re implementing your own code, make sure you store these somewhere safe as part of the user’s details.

Now we have user creation sorted, we need to enable developers to sign up to our API products. Well, I’ve actually done all the hard work for you. Let’s look at a snippet of the code in the Product() method (still in AccountController.cs):

This method intercepts requests from the APIM Developer portal when a user clicks on a subscribe button in one of our API Management Products. It then uses the parameters passed across for the APIM Product’s ID to tell the Stripe API which equivalent Stripe Product Plan we’re signing the user up for (as I mentioned in a previous step, you must make sure when you create a Stripe Pricing Plan that the ID is identical to the associated Product’s ID in API Management). Then we asynchronously retrieve the unique StripeID attribute from our local user database that we saved earlier, and we use this to tell Stripe which customer we want to sign up to the Product we’ve specified. Finally, if the subscription object returned from our Stripe API call has an “Active” status (i.e. the call has been successful and the user’s signed up), we then tell APIM to register the user for the Product. This way, no user can gain access to our APIM Product until they pay up.

Well, why don’t you try it out? If you’re still signed in to the developer portal from the last step, head over to the Products tab (otherwise, sign in or register again first), then click on your Product:

APIM Products

Then click on Subscribe on the Product’s page:

Product sign up - dev portal

This should delegate another call to our website, this time calling the Product()method, which generates a View:

Product sign up - custom codeNow click on Subscribe (for building this out, I’d recommend using this as a Confirm Subscription / payment confirmation page, which I’ll talk about a bit more near the end of this post). This will call the Product() method again, but this time with a “confirm” parameter, which will trigger the code that I referenced in my previous snippet. Should all be successful, you’ll be redirected back to the Developer portal with a shiny new subscription and keys to provide access to the APIs:

API Product subscription successful

Finally, let’s confirm everything is set up on the Stripe side. Head to the dashboard again and click on Subscriptions (https://dashboard.stripe.com/test/subscriptions), and you should hopefully see your Stripe user has been signed up:

Customer subscription successful - Stripe

Excellent, now we can start making money. Stripe will now automatically send a monthly invoice to our customer’s email address and manage payments. Obviously we’re only using a test instance of Stripe here, but we’ve laid the groundwork for other routes of sale, such as collecting card details up front, taking one off payments and more. Stripe has a ton of options here and an expansive API – check out the subscriptions quickstart for more info.

One last step: getting our website into Azure.

Step 6 – Migrating our website to Azure

So, to finish things off, let’s get our website up into Azure. First thing we need to do is Publish it, which is exactly the same process as we used for our Function App earlier:

  1. In Visual Studio, right-click the project in Solution Explorer and click Publish
  2. Click Create new profile, click Microsoft Azure App Service and fill out the form with the desired App Name, subscription, Resource Group & App Plan (you can use the same one as your Function App to save money, if you didn’t choose a Consumption plan), then click Create
  3. Now click Publish and watch the Output window intently

Once your web browser opens up, you know it’s deployed. This is only half the battle however; we were using a local database to run our User store (you can see this under “App_Data” – “UserData.mdf” in the project directory), which won’t be available now our app is in the cloud. To fix this, let’s create a quick SQL database.

I’m going to use the Azure CLI for this, which you can either access via the Cloud Shell in the portal by visiting https://shell.azure.com/ or by installing it on your local machine to use in Bash, Command Prompt or PowerShell, whatever your preference. Or feel free to create a SQL database in the Azure Portal if you’re used to that.

Once you’re logged in, copy the following to the terminal, replace with your desired parameters (good practice to use the same resource group as you used for your webapp) and press Enter:

az sql server create --name griffsdemosqllogicserver --resource-group DemoResources --location WestEurope --admin-user adminUser --admin-password adminPassword

This will create the logical server for our SQL database. Once you get a successful output, enter the following to create the SQL database (make sure you use the same server name as you’ve just created along with the same resource group):

az sql db create --resource-group DemoResources --server griffsdemosqllogicserver --name GriffsDemoSQLDB --service-objective S0

Once that’s deployed, we need to get the connection string that we’ll provide to our webapp in order to access the DB, which you can do like this:

az sql db show-connection-string --name GriffsDemoSQLDB --server griffsdemosqllogicserver --client ado.net --output tsv

Copy the outputted string, paste it into a text editor and add in the username and password you specified when creating the database, replacing the <username> and <password> fields. Then insert it into the statement below (just after DefaultConnection=, change the names to your webapp’s name and resource group, and then execute it in the CLI:

az webapp config connection-string set --name APIMDelegatedAccountMgmt --resource-group DemoResources --connection-string-type SQLAzure --settings "DefaultConnection=YOUR-CONN-STRING-HERE"

You should then get the app’s settings returned to you with our connection string as one of them. This will overwrite the existing connection string we had in the app’s code for the local database, because Azure app settings take precedent. This means we can continue to debug locally using the local database, and then when the app is published, it will use the live database in Azure. Pretty neat.

Final thing we need to do is head back to our API Management portal and update the delegation endpoint to point towards our webapp, instead of our local machine. Head to the Delegation tab and enter in the URL of your webapp, keeping the “/Account/Delegate” suffix:

Delegation live

Hit Save at the top. It will take a couple of minutes to change over, and we’ve got one last thing to do before we test.

Head back to Visual Studio and open up the Package Manager Console. Because we’re using Code-First Migrations on our database, we need to perform a migration on the new Azure SQL Database so that all the attribute columns our app needs are available. Enter the following command into the console, replacing YOUR-CONN-STRING-HERE with, wellas you may have guessed, your Azure SQL DB connection String:

Update-Database -StartUpProjectName "ContosoWebApplication" -ConnectionString "YOUR-CONN-STRING-HERE"

The first time you run this you’ll likely get a big long error output, and this is because the built-in SQL firewall is blocking our access. If so, find the IP address mentioned in the error output like I’ve highlighted and copy it to your clipboard:

IP address for exception

Then go back to the Cloud Shell and insert it into the following command in both the start-ip-address and end-ip-address values:

az sql server firewall-rule create --server griffsdemosqllogicserver --resource-group DemoResources --name AllowPackageManager --start-ip-address YOUR-IP --end-ip-address YOUR-IP

This should update the firewall rules on the SQL Server with an exception for the Package Manager to do it’s thing. Now try again and you should hopefully get this output (if not, wait a couple of minutes in case the firewall rule hasn’t applied yet and try again):

DB migration success

Now we’re finally ready to test. You know the drill: open a private browser window and do the registration process like you did before. If all goes well, you should be greeted by the familiar Developer portal after you’ve signed in:

SUCCESS

And there we have it!

In summary…

We covered a lot there. Thank God for caffeine. We…

  1. Created a serverless API from scratch that resizes images on-demand and interacts with Azure blob storage
  2. Deployed a Function App we wrote and debugged locally to Azure using Visual Studio
  3. Packaged the Function API into an API Management instance and protected the back-end
  4. Applied policies using APIM to transform the API outputs and limit developer calls to a quota
  5. Enabled Delegation and managed user account management in our own custom website application
  6. Added interoperability with the Stripe API to enable monetisation through developer subscriptions & invoicing
  7. Migrated our local webapp to the cloud and transferred the database to Azure SQL using the Azure CLI

I’ll say it again: thank God for caffeine. Now that you have a basic application running a delegation role for APIM and talking to the Stripe API, you’re all set to flesh this out and explore some of the more advanced features both Stripe and API Management have to offer. I wanted to provide a baseline through this post and tie several areas together, so I hope I’ve managed to do that and that you’ve found this guide helpful. If so, please let me know in the comments, and it would be great to hear about what projects you’re considering using some of these services for. If there was anything missing, if you get stuck anywhere, or if you have any requests for another blog post, again, give me a shout below.

Thanks for reading! Until next time, happy API Management-ing.


Leave a Reply

Your email address will not be published. Required fields are marked *