Build a Node.js RESTful API and deploy it to an API app in Azure

This quickstart shows how to create an Express framework Node.js REST API using from a Swagger definition and deploy it as an API app on Azure. You create the app using command-line tools, configure resources with the Azure CLI, and deploy the app using Git. When you've finished, you have a working sample REST API running on Azure.

Prerequisites

If you don't have an Azure subscription, create a free account before you begin.

Launch Azure Cloud Shell

The Azure Cloud Shell is a free Bash shell that you can run directly within the Azure portal. It has the Azure CLI preinstalled and configured to use with your account. Click the Cloud Shell button on the menu in the upper-right of the Azure portal.

Cloud Shell

The button launches an interactive shell that you can use to run all of the steps in this topic:

Screenshot showing the Cloud Shell window in the portal

If you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.0 or later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI 2.0.

Prepare your environment

  1. In a terminal window, run the following command to clone the sample to your local machine.

    git clone https://github.com/Azure-Samples/app-service-api-node-contact-list
    
  2. Change to the directory that contains the sample code.

    cd app-service-api-node-contact-list
    
  3. Install Swaggerize on your local machine. Swaggerize is a tool that generates Node.js code for your REST API from a Swagger definition.

    npm install -g yo
    npm install -g generator-swaggerize
    

Generate Node.js code

This section of the tutorial models an API development workflow in which you create Swagger metadata first and use that to scaffold (auto-generate) server code for the API.

Change directory to the start folder, then run yo swaggerize. Swaggerize creates a Node.js project for your API from the Swagger definition in api.json.

```bash
cd start
yo swaggerize --apiPath api.json --framework express
```

 When Swaggerize asks for a project name, use *ContactList*.
Swaggerize Generator
Tell us a bit about your application
? What would you like to call this project: ContactList
? Your name: Francis Totten
? Your github user name: fabfrank
? Your email: frank@fabrikam.net

Customize the project code

  1. Copy the lib folder into the ContactList folder created by yo swaggerize, then change directory into ContactList.

    cp -r lib/ ContactList/
    cd ContactList
    
  2. Install the jsonpath and swaggerize-ui NPM modules.

    npm install --save jsonpath swaggerize-ui
    
  3. Replace the code in the handlers/contacts.js with the following code:

    'use strict';
    
    var repository = require('../lib/contactRepository');
    
    module.exports = {
        get: function contacts_get(req, res) {
            res.json(repository.all())
        }
    };
    

    This code uses the JSON data stored in lib/contacts.json served by lib/contactRepository.js. The new contacts.js code returns all contacts in the repository as a JSON payload.

  4. Replace the code in the handlers/contacts/{id}.js file with the following code:

    'use strict';
    
    var repository = require('../../lib/contactRepository');
    
    module.exports = {
        get: function contacts_get(req, res) {
            res.json(repository.get(req.params['id']));
        }    
    };
    

    This code lets you use a path variable to return only the contact with a given ID.

  5. Replace the code in server.js with the following code:

    'use strict';
    
    var port = process.env.PORT || 8000; 
    
    var http = require('http');
    var express = require('express');
    var bodyParser = require('body-parser');
    var swaggerize = require('swaggerize-express');
    var swaggerUi = require('swaggerize-ui'); 
    var path = require('path');
    
    var app = express();
    
    var server = http.createServer(app);
    
    app.use(bodyParser.json());
    
    app.use(swaggerize({
        api: path.resolve('./config/swagger.json'),
        handlers: path.resolve('./handlers'),
        docspath: '/swagger' 
    }));
    
    // change four
    app.use('/docs', swaggerUi({
        docs: '/swagger'  
    }));
    
    server.listen(port, function () { 
    });
    

    This code makes some small changes to let it work with Azure App Service and exposes an interactive web interface for your API.

Test the API locally

  1. Start up the Node.js app

    npm start
    
  2. Browse to http://localhost:8000/contacts to view the JSON for the entire contact list.

     {
         "id": 1,
         "name": "Barney Poland",
         "email": "barney@contoso.com"
     },
     {
         "id": 2,
         "name": "Lacy Barrera",
         "email": "lacy@contoso.com"
     },
     {
         "id": 3,
         "name": "Lora Riggs",
         "email": "lora@contoso.com"
     }
    
  3. Browse to http://localhost:8000/contacts/2 to view the contact with an id of two.

    { 
        "id": 2,
        "name": "Lacy Barrera",
        "email": "lacy@contoso.com"
    }
    
  4. Test the API using the Swagger web interface at http://localhost:8000/docs.

    Swagger web interface

Create an API App

In this section, you use the Azure CLI 2.0 to create the resources to host the API on Azure App Service.

  1. Log in to your Azure subscription with the az login command and follow the on-screen directions.

    az login
    
  2. Create a resource group with the az group create command.

    A resource group is a logical container into which Azure resources like web apps, databases, and storage accounts are deployed and managed.

    The following example creates a resource group named myResourceGroup in the westeurope location.

    az group create --name myResourceGroup --location westeurope
    

    To see the available locations, run the az appservice list-locations command. You generally create resources in a region near you.

  3. Create an App Service plan with the az appservice plan create command.

    An App Service plan specifies the location, size, and features of the web server farm that hosts your app. You can save money when hosting multiple apps by configuring the web apps to share a single App Service plan.

    App Service plans define:

    • Region (for example: North Europe, East US, or Southeast Asia)
    • Instance size (small, medium, or large)
    • Scale count (1 to 20 instances)
    • SKU (Free, Shared, Basic, Standard, or Premium)

    The following example creates an App Service plan named myAppServicePlan in the Free pricing tier:

    az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE
    

    When the App Service plan has been created, the Azure CLI shows information similar to the following example:

    { 
      "adminSiteName": null,
      "appServicePlanName": "myAppServicePlan",
      "geoRegion": "West Europe",
      "hostingEnvironmentProfile": null,
      "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
      "kind": "app",
      "location": "West Europe",
      "maximumNumberOfWorkers": 1,
      "name": "myAppServicePlan",
      < JSON data removed for brevity. >
      "targetWorkerSizeId": 0,
      "type": "Microsoft.Web/serverfarms",
      "workerTierName": null
    } 
    
  4. Create a API app in the myAppServicePlan App Service plan with the az webapp create command.

    The web app provides a hosting space for your API and provides a URL to view the deployed app.

    In the following command, replace <app_name> with a unique name. If <app_name> is not unique, you get the error message "Website with given name already exists." The default URL of the web app is https://<app_name>.azurewebsites.net.

    az webapp create --name <app_name> --resource-group myResourceGroup --plan myAppServicePlan
    

    When the web app has been created, the Azure CLI shows information similar to the following example:

    {
      "availabilityState": "Normal",
      "clientAffinityEnabled": true,
      "clientCertEnabled": false,
      "cloningInfo": null,
      "containerSize": 0,
      "dailyMemoryTimeQuota": 0,
      "defaultHostName": "<app_name>.azurewebsites.net",
      "enabled": true,
      "enabledHostNames": [
        "<app_name>.azurewebsites.net",
        "<app_name>.scm.azurewebsites.net"
      ],
      "gatewaySiteName": null,
      "hostNameSslStates": [
        {
          "hostType": "Standard",
          "name": "<app_name>.azurewebsites.net",
          "sslState": "Disabled",
          "thumbprint": null,
          "toUpdate": null,
          "virtualIp": null
        }
        < JSON data removed for brevity. >
    }
    

Deploy the API with Git

Deploy your code to the API app by pushing commits from your local Git repository to Azure App Service.

  1. Configure local Git deployment to the API app with the az webapp source-control config-local-git command.

    App Service supports several ways to deploy content to a web app, such as FTP, local Git, GitHub, Visual Studio Team Services, and Bitbucket. For this quickstart, you deploy by using local Git. That means you deploy by using a Git command to push from a local repository to a repository in Azure.

    Use the script below to set the account-level deployment credentials you'll use when pushing the code, making sure to include your own values for the user name and password.

    az webapp deployment user set --user-name <desired user name> --password <desired password>
    
  2. Initialize a new repo in the ContactList directory.

    git init .
    
  3. Exclude the node_modules directory created by npm in an earlier step in the tutorial from Git. Create a new .gitignore file in the current directory and add the following text on a new line anywhere in the file.

    node_modules/
    

    Confirm the node_modules folder is being ignored with git status.

  4. Commit the changes to the repo.

    git add .
    git commit -m "initial version"
    
  5. Use the Azure CLI to get the remote deployment URL for your API App, then configure your local Git deployment to be able to push to the remote.

    giturl=$(az webapp deployment source config-local-git -n $app_name \ -g myResourceGroup --query [url] -o tsv)
    
    git remote add azure $giturl
    

    Push to the Azure remote to deploy your app. You are prompted for the password you created earlier when you created the deployment user. Make sure that you enter the password you created in earlier in the quickstart, and not the password you use to log in to the Azure portal.

    git push azure master
    

Test the API in Azure

  1. Open a browser to http://app_name.azurewebsites.net/contacts. You see the same JSON returned as when you made the request locally earlier in the tutorial.

    {
        "id": 1,
        "name": "Barney Poland",
        "email": "barney@contoso.com"
    },
    {
        "id": 2,
        "name": "Lacy Barrera",
        "email": "lacy@contoso.com"
    },
    {
        "id": 3,
        "name": "Lora Riggs",
        "email": "lora@contoso.com"
    }
    
  2. In a browser, go to the http://app_name.azurewebsites.net/docs endpoint to try out the Swagger UI running on Azure.

    Swagger Ii

    You can now deploy updates to the sample API to Azure simply by pushing commits to the Azure Git repository.

Clean up

To clean up the resources created in this quickstart, run the following Azure CLI command:

az group delete --name myResourceGroup

Next step