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

9 min to read Contributors

This tutorial shows how to create a simple Node.js API and deploy it to an API app in Azure App Service by using Git. You can use any operating system that can run Node.js, and you'll do all your work using command line tools such as cmd.exe or bash.

Prerequisites

  1. Microsoft Azure account (open a free account here)
  2. Node.js installed (this sample assumes that you have Node.js version 4.2.2)
  3. Git installed
  4. GitHub account

While App Service supports many ways to deploy your code to an API app, this tutorial shows the Git method and assumes that you have basic knowledge of how to work with Git. For information about other deployment methods, see Deploy your app to Azure App Service.

Get the sample code

  1. Open a command line interface that can run Node.js and Git commands.
  2. Navigate to a folder that you can use for a local Git repository, and clone the GitHub repository containing the sample code.

     git clone https://github.com/Azure-Samples/app-service-api-node-contact-list.git
    

    The sample API provides two endpoints: a Get request to /contacts returns a list of names and email addresses in JSON format, while /contacts/{id} returns only the selected contact.

Scaffold (auto-generate) Node.js code based on Swagger metadata

Swagger is a file format for metadata that describes a RESTful API. Azure App Service has built-in support for Swagger metadata. 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.

Note

You can skip this section if you don't want to learn how to scaffold Node.js code from a Swagger metadata file. If you want to just deploy sample code to a new API app, go directly to the Create an API app in Azure section.

Install and execute Swaggerize

  1. Execute the following commands to install the yo and generator-swaggerize NPM modules globally.

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

    Swaggerize is a tool that generates server code for an API described by a Swagger metadata file. The Swagger file that you'll use is named api.json and is located in the start folder of the repository you cloned.

  2. Navigate to the start folder, and then execute the yo swaggerize command. Swaggerize will ask a series of questions. For what to call this project, enter "ContactList", for path to swagger document, enter "api.json", and for Express, Hapi, or Restify, enter "express".

     yo swaggerize
    

    Swaggerize Command Line

    Note: if you encounter an error in this step, the next step explains how to fix it.

    Swaggerize creates an application folder, scaffolds handlers and configuration files, and generates a package.json file. The express view engine is used to generate the Swagger help page.

  3. If the swaggerize command fails with an "unexpected token" or "invalid escape sequence" error, correct the cause of the error by editing the generated package.json file. In the regenerate line under scripts, change the back slash that precedes api.json to a forward slash, so that the line looks like the following example:

      "regenerate": "yo swaggerize --only=handlers,models,tests --framework express --apiPath config/api.json"
    
  4. Navigate to the folder that contains the scaffolded code (in this case, the /start/ContactList subfolder).
  5. Run npm install.

     npm install
    
  6. Install the jsonpath NPM module.

     npm install --save jsonpath
    

    Jsonpath Install

  7. Install the swaggerize-ui NPM module.

     npm install --save swaggerize-ui
    

    Swaggerize Ui Install

Customize the scaffolded code

  1. Copy the lib folder from the start folder into the ContactList folder created by the scaffolder.
  2. Replace the code in the handlers/contacts.js file with the following code.

    This code uses the JSON data stored in the lib/contacts.json file that is served by lib/contactRepository.js. The new contacts.js code responds to HTTP requests to get all of the contacts and return them as a JSON payload.

     'use strict';
    
     var repository = require('../lib/contactRepository');
    
     module.exports = {
         get: function contacts_get(req, res) {
             res.json(repository.all())
         }
     };
    
  3. Replace the code in the handlers/contacts/{id}.js file with the fofllowing code.

     'use strict';
    
     var repository = require('../../lib/contactRepository');
    
     module.exports = {
         get: function contacts_get(req, res) {
             res.json(repository.get(req.params['id']));
         }    
     };
    
  4. Replace the code in server.js with the following code.

    The changes made to the server.js file are called out by using comments so you can see the changes being made.

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

Test with the API running locally

  1. Activate the server using the Node.js command-line executable.

     node server.js
    
  2. When you browse to http://localhost:8000/contacts, you see the JSON output of the contact list (or you're prompted to download it, depending on your browser).

    All Contacts Api Call

  3. When you browse to http://localhost:8000/contacts/2, you'll see the contact represented by that id value.

    Specific Contact Api Call

  4. The Swagger JSON data is served via the /swagger endpoint:

    Contacts Swagger Json

  5. The Swagger UI is served via the /docs endpoint. In the Swagger UI, you can use the rich HTML client features to test out your API.

    Swagger Ui

Create a new API App

In this section you use the Azure portal to create a new API App in Azure. This API app represents the compute resources that Azure will provide to run your code. In later sections you'll deploy your code to the new API app.

  1. Browse to the Azure Portal.
  2. Click New > Web + Mobile > API App.

    New API app in portal

  3. Enter an App name that is unique in the azurewebsites.net domain, such as NodejsAPIApp plus a number to make it unique.

    For example, if the name is NodejsAPIApp, the URL will be nodejsapiapp.azurewebsites.net.

    If you enter a name that someone else has already used, you see a red exclamation mark to the right.

  4. In the Resource Group drop-down, click New, and then in New resource group name enter "NodejsAPIAppGroup" or another name if you prefer.

    A resource group is a collection of Azure resources such as API apps, databases, and VMs. For this tutorial, it's best to create a new resource group because that makes it easy to delete in one step all the Azure resources that you create for the tutorial.

  5. Click App Service plan/Location, and then click Create New.

    Create App Service plan

    In the following steps, you create an App Service plan for the new resource group. An App Service plan specifies the compute resources that your API app runs on. For example, if you choose the free tier, your API app runs on shared VMs, while for some paid tiers it runs on dedicated VMs. For information about App Service plans, see App Service plans overview.

  6. In the App Service Plan blade, enter "NodejsAPIAppPlan" or another name if you prefer.
  7. In the Location drop-down list, choose the location that is closest to you.

    This setting specifies which Azure datacenter your app will run in. For this tutorial, you can select any region and it won't make a noticeable difference. But for a production app, you want your server to be as close as possible to the clients that are accessing it to minimize latency.

  8. Click Pricing tier > View All > F1 Free.

    For this tutorial, the free pricing tier will provide sufficient performance.

    Select Free pricing tier

  9. In the App Service Plan blade, click OK.
  10. In the API App blade, click Create.

Set up your new API app for Git deployment

You'll deploy your code to the API app by pushing commits to a Git repository in Azure App Service. In this section of the tutorial, you create the credentials and Git repository in Azure that you'll use for deployment.

  1. After your API app has been created, click App Services > {your API app} from the portal home page.

    The portal displays the API App and Settings blades.

    Portal API app and Settings blade

  2. In the Settings blade, scroll down to the Publishing section, and then click Deployment credentials.
  3. In the Set deployment credentials blade, enter a user name and password, and then click Save.

    You'll use these credentials for publishing your Node.js code to your API app.

    Deployment Credentials

  4. In the Settings blade, click Deployment source > Choose Source > Local Git Repository, then click OK.

    Create Git Repo

  5. Once your Git repository has been created the blade changes to show you your active deployments. Since the repository is new, you have no active deployments in the list.

    No Active Deployments

  6. Copy the Git repository URL. To do this, navigate to the blade for your new API App and look at the Essentials section of the blade. Notice 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 this icon to copy the URL.

    Get The Git Url From The Portal

    Note: You will need the Git clone URL in the next section so make sure to save it somewhere for the moment.

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.

Deploy your API code to Azure

In this section you create a local Git repository that contains your server code for the API, and then you push your code from that repository to the repository in Azure that you created earlier.

  1. Copy the ContactList folder to a location that you can use for a new local Git repository. If you did the first part of the tutorial, copy ContactList from the start folder; otherwise, copy ContactList from the end folder.
  2. In your command line tool, navigate to the new folder, then execute the following command to create a new local Git repository.

     git init
    

    New Local Git Repo

  3. Execute the following command to add a Git remote for your API app's repository.

     git remote add azure YOUR_GIT_CLONE_URL_HERE
    

    Note: Replace the string "YOUR_GIT_CLONE_URL_HERE" with your own Git clone URL that you copied earlier.

  4. Execute the following commands to create a commit that contains all of your code.

     git add .
     git commit -m "initial revision"
    

    Git Commit Output

  5. Execute the command to push your code to Azure. When you're prompted for a password, enter the one that you created earlier in the Azure portal.

     git push azure master
    

    This triggers a deployment to your API app.

  6. In your browser, navigate back to the Deployments blade for your API app, and you see that the deployment is occurring.

    Deployment Happening

    Simultaneously, the command line interface reflects the status of your deployment while it is happening.

    Node Js Deployment Happening

    Once the deployment has completed, the Deployments blade reflects the successful deployment of your code changes to your API App.

Test with the API running in Azure

  1. Copy the URL in the Essentials section of your API App blade.

    Deployment Completed

  2. Using a REST API client such as Postman or Fiddler (or your web browser), provide the URL of your contacts API call, which is the /contacts endpoint of your API app. The URL will be https://{your API app name}.azurewebsites.net/contacts

    When you issue a GET request to this endpoint, you get the JSON output of your API app.

    Postman Hitting Api

  3. In a browser, go to the /docs endpoint to try out the Swagger UI as it runs in Azure.

Now that you have continuous delivery wired up, you can make code changes and deploy them to Azure simply by pushing commits to your Azure Git repository.

Next steps

At this point you've successfully created an API App and deployed Node.js API code to it. The next tutorial shows how to consume API apps from JavaScript clients, using CORS.