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

This quickstart shows how to create a REST API, written with Node.js Express, using a Swagger definition and deploying it 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.


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 interactive shell that you can use to run the steps in this article. It has common Azure tools preinstalled and configured to use with your account. Just click the Copy to copy the code, paste it into the Cloud Shell, and then press enter to run it. There are a few ways to launch the Cloud Shell:

Click Try It in the upper right corner of a code block. Cloud Shell in this article
Open Cloud Shell in your browser.
Click the Cloud Shell button on the menu in the upper right of the Azure portal. Cloud Shell 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
  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.

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:

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) {

    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) {

    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 fs = require("fs");
    fs.existsSync = fs.existsSync || require('path').existsSync;
    var app = express();
    var server = http.createServer(app);
        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": ""
         "id": 2,
         "name": "Lacy Barrera",
         "email": ""
         "id": 3,
         "name": "Lora Riggs",
         "email": ""
  3. Browse to http://localhost:8000/contacts/2 to view the contact with an id of two.

        "id": 2,
        "name": "Lacy Barrera",
        "email": ""
  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. If you have multiple Azure subscriptions, change the default subscription to the desired one.

    az account set --subscription <name or id>
  3. 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.

  4. 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
  5. Create an 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 <app_name> already exists." The default URL of the web app is https://<app_name>

    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>",
      "enabled": true,
      "enabledHostNames": [
      "gatewaySiteName": null,
      "hostNameSslStates": [
          "hostType": "Standard",
          "name": "<app_name>",
          "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. In the Cloud Shell, create deployment credentials with the az webapp deployment user set command. A deployment user is required for FTP and local Git deployment to a web app. The user name and password are account level. They are different from your Azure subscription credentials.

    In the following example, replace <username> and <password> (including brackets) with a new user name and password. The user name must be unique. The password must be at least eight characters long, with two of the following three elements: letters, numbers, symbols.

    az webapp deployment user set --user-name <username> --password <password>

    If you get a 'Conflict'. Details: 409 error, change the username. If you get a 'Bad Request'. Details: 400 error, use a stronger password.

    You create this deployment user only once; you can use it for all your Azure deployments.


    Record the user name and password. You need them to deploy the web app later.

  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.


    Confirm the node_modules folder is being ignored with git status.

  4. Add the following lines into package.json. The code that's generated by Swaggerize doesn't specify a version for the Node.js engine. Without the version specification, Azure uses the default version of 0.10.18, which isn't compatible with the generated code.

    "engines": {
        "node": "~0.10.22"
  5. Commit the changes to the repo.

    git add .
    git commit -m "initial version"
  6. Use the Azure CLI to get the remote deployment URL for your API App. In the following command, replace <app_name> with your web app's name.

    az webapp deployment source config-local-git --name <app_name> --resource-group myResourceGroup --query url --output tsv

    Configure your local Git deployment to be able to push to the remote.

    git remote add azure <URI from previous step>

    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 You see the same JSON returned as when you made the request locally earlier in the tutorial.

        "id": 1,
        "name": "Barney Poland",
        "email": ""
        "id": 2,
        "name": "Lacy Barrera",
        "email": ""
        "id": 3,
        "name": "Lora Riggs",
        "email": ""
  2. In a browser, go to the 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