
Building, hosting, and consuming your first API App
Let's start with the app.
What is Swagger?
Swagger is open source software that provides powerful metadata representation of your RESTful API. It is a specification for documenting RESTful APIs. It is machine-readable and language agnostic, so there are different implementations for different platforms.
In Azure API Apps, Microsoft adapts Swashbuckle to implement Swagger 2.0. So, the API you create can be easily discoverable using metadata in Swagger 2.0 format, which is widely accepted and supported.
Support for Swagger 2.0 (Refer: http://swagger.io/) API metadata is built into Azure App Service. Each API App can specify a URL endpoint that returns metadata for the API in Swagger JSON format. The JSON metadata returned from that endpoint can be used to generate client code.
If you have a Web API project, then to add Swagger to the project you need to install Swashbuckle via NuGet. Swashbuckle enables the way Swagger metadata is generated for your API. Swashbuckle filters changes how Swagger metadata is generated so that it can include data from the attributes of the API operations.
Once you develop your APIs, they need to be documented so that other developers can quickly understand how to use them. Swagger solves this problem for you by doing a simple but very powerful thing; it generates the REST API descriptions (HTTP methods, URL path, parameters, responses message, HTTP error codes, and so on) and even provides a simple web UI to play with REST calls to your APIs:

Developing and hosting RESTful API App
In this section, we will develop a simple Product API for Sunny Electrical (a fictitious company), which will list all the products from the Product table in Azure SQL database.
Note
In this scenario, we are using Azure SQL database as the data source for the API, but there are various other options for data sources such as on-premise SQL, Oracle, No-SQL database, and Excel. You can also have your API App without any data source.
To develop the RESTful API, there are a couple of prerequisites:
- Azure account: You can create your free Azure account at: https://azure.microsoft.com/en-us/free or you can use Try App Service at: https://tryappservice.azure.com/.
- Visual Studio 2015: Visual Studio 2015 with the Azure SDK for .NET version 2.9 or higher at: https://azure.microsoft.com/en-in/downloads/.
Essentially, we would perform the following tasks:
- Make a SQL connection to the Product table in SQL database in Azure
- Use the Entity Framework Database First Approach to scaffold a CRUD operation
- Create an ASP.Net Web Application using the Azure API App template to expose the operations for the Product table
- Enable Swagger UI and API App testing locally
- Deploy the Product API App in Azure
- View and manage the Product API App in the Azure portal
- Consume a Product API App by generating client code in Visual Studio:

Once you have set up your development environment, you are ready to create your first Azure API App. Let's go ahead and create a new project by navigating to New | Project | ASP.NET Web Application:

Give a suitable name to your ASP.NET Web Application and choose Azure API App from the template dialog box:

Click on OK, and Visual Studio creates your ProductApi
project. Now you will see, by default, that the Swashbuckle NuGet package has been added to the reference. Swashbuckle seamlessly adds a Swagger to Web API projects. In our case, it uses ASP.NET Web API help methods to reflect our Web API automatically in Swagger.
Now we will connect to the Product table in the SQL Azure database, AzureProductDb, and use it as a model class for our ProductApi
. You can refer to the azure documentation to create SQL database using an Azure portal at: https://azure.microsoft.com/en-in/documentation/articles/sql-database-get-started/ :

To connect to a SQL database in Azure, we need to perform the following tasks:
- Add a client IP to the database server firewall rule in the Azure portal
- Provide the database server name that hosts your SQL database in the following format:
<servername>.database.windows.net
- Provide a username and password using SQL Server authentication
- Select the required database and click on OK
We will add ADO.Net Entity Data Model by right-clicking on the Models
folder and selecting the Data tab. Enter the name for your model; in our case, it will be Product
. Click on the Add
button:

In the Entity Data Model Wizard, select the EF Designer from database option and click on Next, as shown in the following image:

As discussed earlier, now we need to provide the Azure SQL Server name, database name, and credentials to make a successful connection:

Test the connection by clicking on the Test Connection button.
Since we have provided vital information, such as, username and password to connect to the Azure database server, the Entity Data Model Wizard provides an option to include sensitive data in the connection string or not. Here, we'll select the Yes radio button and click on Next. Also, if you want, you can change the connection string name here:

Now we need to select the entity to work with. In our case, it would be the Product table, as shown here:

Next, to create the data model, click on Finish and we have added the Product
model in the Solution Explorer, as shown in the upcoming image. The Product
model is basically a class that models the shape of API inputs/outputs:

We will use this Product
model to create the API App. Make sure that you have successfully built the project at this stage and then let's create a controller. Controllers are the classes where we implement the core logic within the methods to handle incoming HTTP requests.
Go to the Controller
folder and delete the default ValuesController
and add a new Controller
.
In the scaffolding option,select Web API 2 Controller with actions, using Entity Framework , and click on the Add button:

To add the Controller using the scaffolding, you need to select the following options:
- Model class: Choose Product from the drop-down
- Data context class: Choose AzureProductDbEntities from the drop-down
Either give your desired Controller a name or leave the suggested name that is based on the Model class:

After clicking on Add, the ProductsController
would be added to the project as shown here:

Essentially, we have created web API to perform CRUD operations on the Product table. In the next step, we have to enable the Swagger UI.
Enabling the Swagger UI
As mentioned earlier in the Swagger section, Swagger provides a simple web UI for the API descriptions such as HTTP methods, URL path, parameters, responses message, and HTTP error codes. In this section, we will see how to enable the Swagger UI for the Product API App.
If you build and run the project, the browser opens and shows the HTTP 403 error page:

Since API Apps supports Swagger, the REST API defines an endpoint URL that returns metadata for the API in the Swagger JSON format. To get JSON metadata for the API, in your browser address bar, add swagger/docs/v1
to the end of the line (that is, http://localhost:21862/swagger/docs/v1
) and then press Return:

This is the Swagger 2.0 JSON metadata for the ProductApi
, which can be used to create the client code.
This metadata is also responsible for generating the Swagger UI. To enable the Swagger UI, go back to the project, open the App_Start\SwaggerConfig.cs
file, then scroll down to the following code and uncomment it:

Run the project again. In your browser address bar, add swagger to the end of the line (that is, http://localhost:21862/swagger
) and then press Return:

Testing your API
Using Swagger UI, we can test a ProductApi
we created. Let's test the couple of things:
- POST: Create a product
- GET: List all the products
Click on POST and then click on the box under Model Schema. Clicking on Model Schema prefills the input box where you can specify the parameter value for the Post
method. Change the JSON in the product parameter input box as shown here:

Click on Try it out!. The ProductApi
returns an HTTP 201
response code that indicates success:

Click on the first GET button and then, in that section of the page, click on the Try it out! button. The Get
method response now includes the new product:

Deploying ProductAPI to Azure
So far, we have developed our ProductApi
locally and tested it using Swagger UI. Now we would use Visual Studio's integrated tool, the Publish Web wizard, to create a new API App in Azure and then deploy the ProductApi
to a new API App.
Note
Make sure that you are using the latest SDK version. Refer to https://azure.microsoft.com/en-us/downloads/ to download the latest SDK.
To open the Publish Web wizard, right-click on the ProductApi
project in Solution Explorer and then click on Publish.
In the Profile step of the Publish Web wizard, click on Microsoft Azure App Service. Sign in to your Azure account:

In the App Service dialog box, choose the Azure subscription you want to use and then click on New :

Select an API App type from the Change Type drop-down list to confirm that you are hosting the API App in the App Service. Now enter a unique name for your API App or accept the default name that Visual Studio proposes. The URL of the API App will be {APi app name}.azurewebsites.net
.
In the following screenshot, you can see sample values for API App Name and Resource Group, and these values would be different for your API App:

A Resource Group is a container for all your resources such as API Apps, Web Apps, databases, and VMs. It's good to create a new resource group to keep all related resources together according to your requirements. This may be by region, capacity, business process, or administration. All resources in the same group should share the same life cycle for deploying, updating, or deleting all together.
An App Service Plan determines the set of features and capacity you require for your apps and services to use. So, primarily an App Service Plan specifies the compute resources that your API App runs on.
Also, it allows you to group several Azure resources together to share a single pricing tier thereby reducing costs. For example, if you choose the free tier, your API App runs on shared VMs, whereas, for some paid tiers, it runs on dedicated VMs:

For further details about Resource Groups and App Service Plans, please refer to the previous chapter.
To create an App Service Plan for the Resource Group, SunnyElectricalAppServices
, click on the New button next to the App Service Plan drop-down. In the Configure App Service Plan dialog, enter SunnyElectricalAppPlan
or another name of your choice. In the Location drop-down list, choose the location that is closest to you. In the Size drop-down list, click on Free and then click on OK:

In the Create App Service dialog box, click on Create. In the background, Visual Studio reaches out to your Azure subscription to create the API App and downloads the publish profile that has all the required settings for the API App:

The Publish Web wizard opens on the Connection tab, as shown later. The Connection tab shows the Server and Site name settings point to your API App along with the User name and Password are deployment credentials that Azure creates for you. Now click on Next:

The Settings tab allows you to change the build configuration and several File Publish Options, as follows:
- Remove additional files at destination
- Precompile during publishing
- Excludes files from the App_Data folder
Here, you can also change the build Configuration tab to deploy a Debug build for remote debugging (refer to: https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-dotnet-troubleshoot-visual-studio#remotedebug).
Click on Next to go to the Preview tab:

We are not using any of the File Publish Options here. For detailed explanations of what they do and other depolyments options, refer to https://msdn.microsoft.com/library/dd465337.aspx .
If you click on the Start Preview button on the Preview tab, it will list all the files that are going to be copied from your project to the API App. Now click on Publish:

Visual Studio deploys the ProductApi
project to the new API App in Azure. You can see the success message in the Output window logs once the deployment is completed successfully:

Also, a successfully created page would appear in a browser window opened to the URL of the API App:

Add swagger
to the URL in the browser's address bar (that is, http://{apiappname}.azurewebsites.net/swagger
) and then press Enter.
The browser displays the same Swagger UI that you saw earlier, but now it's running in the cloud. Try testing a couple of scenarios that we previously tried locally.
- GET: List all the products
- POST: Create a product
You should see the same results, but the changes made now would be saved in Azure instead your local machine:

Viewing and managing the ProductAPI in Azure portal
An Azure portal provides a visual dashboard as a web interface to monitor and manage Azure resources such as API Apps.
Open the Azure portal from https://portal.azure.com . Navigate to Browse | App Services:

In the App Services blade (windows that open to the right are named blades), find and click on your new API App:

In the Settings blade, find the API section and click on API definition:

The API definition blade lets you specify the URL that returns Swagger 2.0 metadata in the JSON format. When Visual Studio creates the API App, it sets the API definition URL to the default value for Swashbuckle-generated metadata that you saw earlier, which is the API App's base URL plus /swagger/docs/v1
:

When you select an API App to generate client code for it, Visual Studio retrieves the metadata from this URL.
Consuming your API App by generating client code in Visual Studio
Integrating Swagger into Azure API Apps makes it very easy to generate built-in client code in Visual Studio. Generated client code makes it easier to write code that calls an API App.
In Visual Studio Solution Explorer, add a new console application project and give it a suitable name.
Now, right-click on the console (ProductClient) project and then navigate to Add | REST API Client:

In the Add REST API Client dialog box, click on Swagger Url and then click on Select Azure Asset:

In the App Service dialog box, expand the Resource Group, select the one you're using for your API App, select the API App and then click on OK:

Note that when you return to the Add REST API Client dialog, the text box has been filled in with the API definition URL value that you saw earlier in the Azure Portal (mention the figure).
Alternatively, you can also use the Swagger JSON file, which you can get by going to the same URL, http://productapi20160623.azurewebsites.net/swagger/docs/v1
.
Save the JSON file and use the Select an existing Swagger metadata file option:

In the Add REST API Client dialog box, click on OK. Visual Studio creates a folder named after the API App and generates client classes, as shown here:

The following code snippet shows how to instantiate the client object and calls the Get
method:

Run the client project to see the product details in the console:

At this point, we have successfully created the Product API App using Visual Studio and then deployed it in Azure using the Publish Web wizard tool. We also generated client code for API Apps and consumed the Product API Apps from the .NET console client application.
The API App's architecture
In a nutshell, API Apps make it easy to build and consume your APIs in the cloud. It provides a rich platform and ecosystem for building, consuming, and distributing APIs in cloud and on-premise:

We already created a sample API (ProductApi
), deployed it in Azure, and easily consumed it in visual studio using built-in automatic client code generation feature. We briefly touched the Resource Group concept, which is basically a container for your app. All things related to your app can live in the same resource group.
Along with our custom APIs, we also have managed APIs built by Microsoft in Marketplace gallery, which we can pull in our application to connect other SaaS application such as Salesforce and Office365. These managed APIs are also named connectors, which we will discuss in detail in Chapter 6, Working with Connectors in Logic Apps.
One of the design principles of API Apps allow you to bring your API as is, in the language of your choice. The other important feature is to turn on simple authentication that expands service-to-service and user authentication. It also expands to a number of identity providers including Azure Active Directory (AAD) as well as social providers such as Facebook and Google.
You can also enable cross-origin resource sharing (CORS)feature, which allows cross-domain browser access so that you can call your API in HTML and JavaScript web clients.
Because an API App is a part of App Service, it inherits the feature of hybrid connectivity and virtual networks. So, you can use the API App to build a cloud API, which is modern and REST on the top of the on-premise API that might not be REST and might be behind your enterprise firewall.
In the next sections of this chapter, we will explore all the key feature Authentication and CORS, and it will also see how you can bring your API as is and deploy it as an API App.
The CORS support
Understanding CORS
As defined on Wikipedia,
"CORS allows many resources on a web page to be requested from another domain outside the domain from which the resource originated."
In other words, CORS defined a way that a browser application can interact safely with a service that originates in a different domain or even a different server.
CORS enables HTML and JavaScript web clients to make cross-domain calls to APIs that are hosted in API Apps.
To understand more clearly, let's create a simple AngularJS website that lists all the products by calling our ProductApi
.

Now when I run this website locally, it will not show up the list because the ProductApi
call will fail. The browser's developer tool's Console window shows a cross-origin error message, as shown here:

The reason for failure is that the frontend is running in a different domain (http://localhost:35725/
) than the backend (http://productapi20160623.azurewebsites.net/
).
Enabling CORS in Azure App Service
Now we will configure CORS settings in Azure for ProductApi
, which will allow JavaScript calls from the website.
In a browser, go to the Azure portal at https://portal.azure.com. Click on App Service
and then click on the ProductApi App.

In the Settings blade that opens to the right of the API App blade, find the API section and then click on CORS.

In the text box, enter the URL for the website, http://localhost:35725
. If you have deployed your frontend app in Azure, then you need to enter http://{frontendappname}.azurewebsites.net
.
As an alternative, you can enter an asterisk (*
) to specify that all origin domains are accepted. Now click on Save.

Now that we have enabled CORS, the ProductApi
App will accept JavaScript calls from the specified URL. Now if we try running the website, it will list the products as shown here:

In this section, you saw how to enable App Service CORS support so that client JavaScript code can call an API in a different domain.
Bringing your APIs as-is
You can bring in your API as-is,in the language of your choice, and deploy it as API App in Azure. This would enable your existing API to take advantage of the features of the API Apps in Azure App Service—with no code changes. You can use ASP.NET, Java, PHP, Node.js, or Python for your APIs. API Apps can be used with the same SDK as Mobile Apps, so your code can easily be used on devices and the web.
To demonstrate this feature I have developed the same ProductApi
in Node.js (https://nodejs.org/en/) and we will see how we can deploy it as API App in Azure App Service.
We are using the Visual Studio Code editor (https://code.visualstudio.com/docs/runtimes/nodejs ) to write the Node.js application but you can use any editor of your choice.

Here I am using MongoDB to store the product details with the same Product model as we used before.
Note
MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. For further details please refer to: https://www.mongodb.com/.

I am using the node-restful (https://github.com/baugarten/node-restful) library to quickly build a REST API with express.

Testing an API using Postman
We can use the free tool Postman (https://www.getpostman.com) to test the productApi
we created in Node.Js. You can use either of the Chrome extension or Chrome app to test the API. We are using the Chrome app to test the API, as shown here:

This tool is very clean and easy to use. It basically allows you to generate all the HTTP requests to your API, that is, GET, POST, PUT, and DELETE.
So first, I will create the GET request by entering the URL for the API: http://localhost:3000/api/products
.
When we send the request, it would return nothing as we have not created any product yet.

Now, let's add a couple of products, same as we have in our Product API App.

After adding the products, let's send the GET request again to list down the products we created.

Creating a new API App
Now that we have tested the API locally, we will deploy it to Azure. To deploy our node.js API first, we need to create a new API App in Azure using the Azure Portal.
Open the Azure Portal: https://portal.azure.com . Navigate to New | Web + Mobile | API App.

Enter a unique App name and then, in the Resource Group drop-down, click on Create new Then, in new Resource Group name, enter NodejsAPIAppGroup
or another name if you prefer.
Now click on App Service plan/Location and then click on Create New.

This would create a new App Service plan for the new Resource Group where your API App runs on. For example, if you choose the free tier, your API App runs on shared VMs, whereas for some paid tiers it runs on dedicated VMs.
In the App Service plan blade, enter NodejsAPIAppPlan
or another name if you prefer, and in the Location drop-down list choose the location that is closest to you.
Now navigate to Pricing tier | View All | F1 Free. For this node API, the free pricing tier will provide sufficient performance. Refer to the following screenshot:

Now in the App Service plan blade, click on OK and then in the API App blade, click on Create.
Setting up the deployment source for your new API App
Now the node API App is created, we would set the Git repository in Azure App Service to deploy our node API code.
Navigate to App Services | {your API App}
from the portal home page, which would display the API App and Settings blades. Then, in the Settings blade, scroll down to the PUBLISHING section and then click on Deployment credentials.

These credentials would be used in order to publish the Node.js code to the API App.
Now in the Settings blade, navigate to Deployment source | Choose Source | Local Git Repository, then click on OK.

Once your Git repository has been created, you can check your active deployments, as shown later. Because the repository is new, you have no active deployments in the list.

Navigate to the blade for your new API App and look at the Essentials section of the blade. Note the Git clone url in the Essentials section. When you hover over this URL, you see an icon on the right that will copy the URL to your clipboard. Click on this icon to copy the URL.

Now that you have an API App with a Git repository backing it up, you can push code into the repository to deploy the code to the API App.
Deploying Node.js API code to Azure
Now we would create a local Git repository that contains Node.js code for the API and then we will push the code from that repository to the repository in Azure that we created earlier.
Create a folder location to use it for a new local Git repository and copy your Node.js ProductApi
code there.
Now in your command-line tool, navigate to the new folder, then execute the following command to create a new local GIT repository:
git init
Execute the following command to add a Git remote for your API App's repository:
git remote add azure YOUR_GIT_CLONE_URL_HERE
Replace the string YOUR_GIT_CLONE_URL_HERE
with your own Git clone URL that you copied earlier.
Now execute the following commands to create a commit that contains all of your code:
git add git commit -m "first version"
Now push the code to Azure by executing the following command:
git push azure master
When you're prompted for a password, enter the one that you created earlier in the Azure portal. This will now trigger a deployment to your API App.
Once the deployment has completed, the Deployments blade reflects the successful deployment of your code changes to your API App.
Now, again using the Postman, we will get the API running in Azure.

At this point, we have successfully created an API App and deployed Node.js API code to it. We also tested the API App using the Postman tool.
In the next section of this chapter, we will see the different ways to secure our API App in Azure.