How To Write NodeJS REST API With Azure Functions

NodeJS is a popular platform for building server-side applications due to its scalability, performance, and ease of use. Azure Functions, on the other hand, are a serverless compute service that lets you run code on-demand without the need to manage infrastructure. By combining these two technologies, you can build a highly scalable and flexible REST API with minimal setup and maintenance.

Untitled design 1
How To Write NodeJS REST API With Azure Functions

In this article, we will walk through the steps to create a NodeJS REST API with Azure Functions. We will start by setting up a new Azure Functions project and then we will create a simple API endpoint to retrieve a list of users.

Prerequisites Before we begin, make sure you have the following:

  1. An Azure account: You can sign up for a free account if you don’t have one already.
  2. NodeJS installed on your machine: You can download NodeJS from the official website.
  3. Azure Functions Core Tools: You can install Azure Functions Core Tools by following the instructions on the official documentation.

Step 1:

Create a new Azure Functions project To create a new Azure Functions project, open a command prompt or terminal window and navigate to the folder where you want to create the project. Then, run the following command:

func init <project-name> --node

This command will create a new Azure Functions project with the specified name and using NodeJS as the runtime. Once the project is created, navigate to the project folder by running the following command:

cd <project-name>

Step 2:

Create a new Azure Function Next, we will create a new Azure Function to handle the API endpoint. To do this, run the following command:

func new --name getUsers --template "HTTP trigger"

This command will create a new Azure Function named “getUsers” with an HTTP trigger template. The HTTP trigger template sets up a basic HTTP endpoint that can be used to receive and respond to HTTP requests.

Step 3:

Implement the getUsers function Once the function is created, open the “getUsers/index.js” file and replace the contents with the following code:

module.exports = async function (context, req) {
    const users = [
        { id: 1, name: "John Doe" },
        { id: 2, name: "Jane Doe" },
        { id: 3, name: "Bob Smith" },
    ];

    context.res = {
        body: users
    };
};

This code creates an array of user objects and sets the response body to the array. When a request is made to this endpoint, it will return the array of users as the response.

Step 4:

Test the API To test the API, run the following command to start the Azure Functions host:

func host start

Once the host is started, open a web browser and navigate to “http://localhost:7071/api/getUsers“. You should see the list of users displayed in the browser.

Step 5:

Deploy the API to Azure Now that the API is working locally, we can deploy it to Azure. To do this, run the following command to create a new Azure Functions app:

az functionapp create --name <app-name> --consumption-plan-location <location> --resource-group <resource-group-name> --runtime node

Replace “<app-name>”, “<location>”, and “<resource-group-name>” with your desired values. This command will create a new Azure Functions app with the specified name and location.

Next, run the following command to deploy the Azure Function to the new app:

func azure functionapp publish <app-name>

This command will publish the Azure Function to the app created in the previous step.

Step 6:

Test the deployed API To test the deployed API, navigate to the Azure portal and open the function app that was created in the previous step. Then, click on the “getUsers” function and select the “Test” tab. In the “Request body” section, leave it blank as we are not sending any data for this request. Then, click on the “Run” button. You should see the list of users displayed in the “Response body” section.

Step 7:

Add authentication to the API To add authentication to the API, we will use Azure Active Directory (AAD). First, create a new AAD app registration in the Azure portal. To do this, navigate to the Azure portal and go to “Azure Active Directory” -> “App registrations” and click on “New registration”. Give the app a name and select “Accounts in this organizational directory only” as the supported account type.

Once the app is created, go to the “Certificates & secrets” tab and click on “New client secret” to create a new client secret. Copy the value of the client secret as we will use it later.

Next, go to the “API permissions” tab and click on “Add a permission”. Select “Microsoft Graph” as the API and then select “Application permissions”. Scroll down and select “User.Read” and then click on “Add permissions”.

Finally, we need to update the code for the “getUsers” function to check for the presence of an AAD access token and validate it. Replace the code in the “getUsers/index.js” file with the following:

const msRestNodeAuth = require("@azure/ms-rest-nodeauth");

module.exports = async function (context, req) {
    let accessToken = null;

    try {
        const authResponse = await msRestNodeAuth.loginWithServicePrincipalSecret(
            process.env.AZURE_CLIENT_ID,
            process.env.AZURE_CLIENT_SECRET,
            process.env.AZURE_TENANT_ID
        );

        accessToken = authResponse.accessToken;
    } catch (error) {
        context.log.error(error);
        context.res = {
            status: 500,
            body: { error: "Failed to authenticate with Azure AD." },
        };
        return;
    }

    if (!req.headers.authorization || req.headers.authorization.indexOf("Bearer ") === -1) {
        context.res = {
            status: 401,
            body: { error: "Authorization token not found." },
        };
        return;
    }

    const token = req.headers.authorization.split(" ")[1];

    if (accessToken !== token) {
        context.res = {
            status: 401,
            body: { error: "Invalid authorization token." },
        };
        return;
    }

    const users = [
        { id: 1, name: "John Doe" },
        { id: 2, name: "Jane Doe" },
        { id: 3, name: "Bob Smith" },
    ];

    context.res = {
        body: users
    };
};

This code uses the “@azure/ms-rest-nodeauth” package to authenticate with AAD using the client ID, client secret, and tenant ID. If authentication is successful, it checks for the presence of an access token in the request headers and validates it against the AAD access token. If validation is successful, it returns the list of users.

Step 8:

Deploy the updated API to Azure To deploy the updated API to Azure, run the following command to publish the function to the app:

func azure functionapp publish <app-name>

Make sure to replace “<app-name>” with the name of your Azure Functions app. Once the deployment is complete, the updated API will be available for testing.

Step 9:

Test the authenticated API To test the authenticated API, first generate an AAD access token using the client ID, client secret, and tenant ID of the AAD app registration. You can do this using a tool like Postman or cURL.

Once you have the access token, send a GET request to the API endpoint with the access token in the “Authorization” header:

GET https://<app-name>.azurewebsites.net/api/getUsers
Authorization: Bearer <access-token>

Make sure to replace “<app-name>” with the name of your Azure Functions app and “<access-token>” with the AAD access token. You should see the list of users displayed in the response.

Conclusion

In this article, we have seen how to create a Node.js REST API using Azure Functions. We have also added authentication to the API using Azure Active Directory. By following the steps outlined in this article, you can easily create and deploy your own REST API using Azure Functions.

FQA

azure function javascript call rest api

To call a REST API from an Azure Function written in JavaScript, you can use the built-in http module or a third-party library like axios. Here’s an example of how to use axios to call a REST API from an Azure Function:

const axios = require('axios');

module.exports = async function (context, req) {
    try {
        const response = await axios.get('https://api.example.com/data');
        context.res = {
            body: response.data
        };
    } catch (error) {
        context.log.error(error);
        context.res = {
            status: error.response.status,
            body: error.response.data
        };
    }
};

In this example, we’re using axios to make a GET request to a REST API at https://api.example.com/data. If the request is successful, we set the response body to the data returned by the API. If there’s an error, we log the error to the Azure Function’s context and set the response status and body to the error information returned by the API.

You can modify this example to make POST, PUT, or DELETE requests by changing the HTTP method in the axios call. Additionally, you can pass data to the API by including it in the request body or query parameters.

azure function rest api

Azure Functions can be used to create REST APIs using a variety of programming languages, including C#, Java, Python, and Node.js. Here’s a high-level overview of the steps involved in creating a REST API with Azure Functions:

  1. Choose a programming language and development environment: Depending on your skillset and project requirements, you can choose a programming language and development environment that’s supported by Azure Functions.
  2. Define the API routes: Define the API routes that your Azure Function will handle. This includes the HTTP method (GET, POST, PUT, DELETE, etc.) and the URL endpoint that the API will be accessed at.
  3. Implement the API logic: Write the code that will handle incoming API requests and return responses to the client. This can include database queries, authentication and authorization logic, and other business logic as needed.
  4. Test and deploy the API: Test the API locally to ensure it’s working as expected, then deploy it to Azure Functions for public access. You can deploy the API manually or use automated deployment tools like Azure DevOps or GitHub Actions.
  5. Secure the API: Implement security measures to protect your API from unauthorized access and ensure that client requests are authenticated and authorized.

Once your REST API is up and running, you can monitor and scale it as needed using Azure Functions’ built-in monitoring and scaling tools. You can also integrate your API with other Azure services, like Azure Storage or Azure Cosmos DB, to create more robust and scalable applications.

run node js azure function locally

To run a Node.js Azure Function locally, you can use the Azure Functions Core Tools. Here are the steps:

  1. Install Azure Functions Core Tools: Install the Azure Functions Core Tools by running the following command in your terminal or command prompt:
npm install -g azure-functions-core-tools

Create a new Azure Function: Create a new Azure Function by running the following command in your terminal or command prompt:

func init MyFunction --javascript

This command creates a new Azure Function project in a directory called MyFunction using the JavaScript runtime.

  1. Write your Azure Function: Write your Azure Function code in the MyFunction directory. You can use your preferred text editor or IDE to edit the code.
  2. Run the Azure Function: To run your Azure Function locally, run the following command in your terminal or command prompt:
func start

This command starts the Azure Functions runtime and runs your function locally. You should see output in your terminal or command prompt indicating that the function is running.

  1. Test the Azure Function: Test your Azure Function by sending an HTTP request to the local endpoint. You can use tools like Postman or cURL to send HTTP requests to the local endpoint.

By following these steps, you can run your Node.js Azure Function locally and test it before deploying it to Azure.

azure function python rest api

Azure Functions can also be used to create REST APIs using Python. Here’s an overview of the steps involved in creating a Python-based REST API with Azure Functions:

  1. Install Azure Functions Core Tools: First, install the Azure Functions Core Tools by following the instructions provided in the official documentation for your operating system.
  2. Create a new Azure Functions project: Next, create a new Azure Functions project in your preferred directory by running the following command:
func init MyPythonFunction --python

This creates a new Python-based Azure Functions project in a directory called MyPythonFunction.

  1. Create a new Azure Function: Once your project is created, create a new Azure Function within it by running the following command:
func new --name MyFunction --template "HTTP trigger"

This command creates a new Azure Function named MyFunction with an HTTP trigger template, which allows it to be accessed via HTTP requests.

  1. Write the API logic: Write the code that will handle incoming API requests and return responses to the client. This can include database queries, authentication and authorization logic, and other business logic as needed.
  2. Test the Azure Function locally: To test the Azure Function locally, run the following command:
func start

This starts the Azure Functions runtime and runs your function locally. You can test it using a tool like Postman by sending an HTTP request to the local endpoint.

  1. Deploy the Azure Function to Azure: Once you’ve tested your Azure Function locally and are satisfied with its behavior, you can deploy it to Azure using the Azure Functions Core Tools or the Azure portal.

By following these steps, you can create a Python-based REST API with Azure Functions and deploy it to Azure for public access.

azure function connect to sql database node js

To connect an Azure Function written in Node.js to a SQL database, you can use the mssql module. Here’s an overview of the steps involved:

  1. Install the mssql module: First, install the mssql module by running the following command in your function project directory:
npm install mssql
  1. Import the mssql module: Next, import the mssql module in your function code by adding the following line at the top of your code file:
const sql = require('mssql');
  1. Set up the database connection: Use the sql module to set up a connection to your SQL database by adding the following code to your function:
const config = {
    user: '<your-database-username>',
    password: '<your-database-password>',
    server: '<your-database-server>',
    database: '<your-database-name>'
};

sql.connect(config, err => {
    if (err) {
        console.log(err);
    } else {
        console.log('Connected to SQL database');
    }
});

Replace the values in the config object with the credentials and connection details for your SQL database.

  1. Run SQL queries: Once you have set up the database connection, you can use the sql module to run SQL queries in your function. For example:
sql.query('SELECT * FROM MyTable', (err, result) => {
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
});

This code executes a SQL query to select all rows from a table named MyTable.

By following these steps, you can connect your Azure Function written in Node.js to a SQL database and run SQL queries within your function code.

How do I create a REST API with Azure Functions?

To create a REST API with Azure Functions, you can follow these steps:

  1. Create a new Azure Functions project: First, create a new Azure Functions project in your preferred directory by using the Azure Functions Core Tools or the Azure portal.
  2. Create a new HTTP trigger function: Within your project, create a new HTTP trigger function. This function will handle incoming HTTP requests and return responses to the client. You can create this function using the Azure Functions Core Tools or the Azure portal.
  3. Write the API logic: Write the code that will handle incoming API requests and return responses to the client. This can include database queries, authentication and authorization logic, and other business logic as needed.
  4. Define API routes: Define the routes for your API by specifying the HTTP methods and URL paths that your API will handle. You can use a framework like Express.js or Fastify to define these routes.
  5. Test the API locally: To test your API locally, run your Azure Functions project and send HTTP requests to the local endpoint using a tool like Postman.
  6. Deploy the API to Azure: Once you’ve tested your API locally and are satisfied with its behavior, you can deploy it to Azure using the Azure Functions Core Tools or the Azure portal.

By following these steps, you can create a REST API with Azure Functions and deploy it to Azure for public access.

How do I deploy a node JS REST API to Azure?

To deploy a Node.js REST API to Azure, you can follow these steps:

  1. Create an Azure Function App: First, create an Azure Function App using the Azure portal or the Azure Functions Core Tools. This app will host your Node.js REST API and allow it to be accessed publicly.
  2. Configure the deployment settings: Configure the deployment settings for your Azure Function App by specifying the deployment source and other settings. You can use a variety of deployment options, including Azure DevOps, GitHub, or local Git repositories.
  3. Build your Node.js REST API: Build your Node.js REST API using the tools and libraries of your choice. Be sure to include any necessary dependencies in your package.json file.
  4. Publish your Node.js REST API: Publish your Node.js REST API to Azure using the deployment method you specified in step 2. This will upload your Node.js code to Azure and make it available for use.
  5. Configure your Node.js REST API: Configure your Node.js REST API by setting up environment variables, connection strings, and other configuration settings as needed. You can use the Azure portal or the Azure Functions Core Tools to configure your API.
  6. Test your Node.js REST API: Test your Node.js REST API by sending HTTP requests to its public endpoint using a tool like Postman.

By following these steps, you can deploy a Node.js REST API to Azure and make it publicly available for use.

Can I call API from Azure function?

Yes, you can call an API from an Azure Function. Azure Functions are designed to be lightweight and scalable, and they can easily make HTTP requests to external APIs.

To call an API from an Azure Function, you can use a library or package that provides HTTP client functionality. For example, in a Node.js-based Azure Function, you can use packages like axios or node-fetch to make HTTP requests to an API.

Here is a sample code snippet for calling an API from an Azure Function:

const axios = require('axios');

module.exports = async function (context, req) {
    try {
        const apiUrl = 'https://api.example.com/data';
        const response = await axios.get(apiUrl);
        context.res = {
            body: response.data
        };
    } catch (error) {
        context.log(error);
        context.res = {
            status: 500,
            body: 'Error fetching data from API'
        };
    }
};

In this example, the Azure Function uses the axios package to make a GET request to an external API at https://api.example.com/data. If the request is successful, the function returns the API response in the function response body. If there is an error, the function logs the error and returns a 500 error status and an error message in the response body.

By using an HTTP client library like axios, you can easily call an API from an Azure Function and handle the API response in your code.

nodejs azure functions configure

Configuring Node.js Azure Functions involves setting up your development environment, creating an Azure Functions app, and configuring various settings. Here are the basic steps to configure a Node.js Azure Function:

  1. Set up your development environment: You will need to have Node.js and the Azure Functions Core Tools installed on your local machine. You can install Node.js from the official website, and the Azure Functions Core Tools can be installed using npm.
  2. Create an Azure Functions app: You can create an Azure Functions app using the Azure portal or Azure CLI. Choose a unique name for your app and select the hosting plan and region.
  3. Configure app settings: You can configure various settings for your Azure Functions app, such as connection strings, environment variables, and logging options. You can do this through the Azure portal or using Azure CLI commands.
  4. Write your Node.js Azure Function: Write the code for your Azure Function in your preferred code editor, using the Azure Functions Core Tools to test and debug your code locally.
  5. Deploy your Azure Function: You can deploy your Azure Function to the Azure Functions app using the Azure CLI or through the Azure portal.
  6. Test your Azure Function: Once deployed, you can test your Azure Function using tools like Postman or Azure Functions’ built-in testing features.

By following these steps, you can configure your Node.js Azure Functions app and deploy your RESTful API to Azure.

External website for more

Avatar of suneel kumar

I am a software development engineer with two years of experience, and I have a passion for creating coding blogs that provide valuable insights to fellow developers. In my free time, I enjoy reading books and articles that help me enhance my skills and produce high-quality content for my readers.

Sharing Is Caring:

2 thoughts on “How To Write NodeJS REST API With Azure Functions”

Leave a Comment