Building Azure HTTP Trigger Function to Generate QR Codes from Post Request Responses

Introduction

Azure Functions provides a serverless computing platform that allows you to build, deploy, and scale applications seamlessly. In this tutorial, i will guide you through the process of creating an Azure HTTP Trigger Function using Node.js. The goal is to generate QR codes in response to POST requests.

Prerequisites

  1. Azure Account: Ensure you have an active Azure account. If you don't have one, you can sign up for a free account at Azure Portal.
  2. Azure Functions Extension: Install the Azure Functions extension for Visual Studio Code. This extension provides tools for creating, deploying, and managing Azure Functions directly from your development environment.
  3. Node.js and npm: Install Node.js and npm (Node Package Manager) on your machine. You can download them from the official Node.js website.
  4. Visual Studio Code: Install Visual Studio Code or any other preferred code editor. Visual Studio Code provides excellent support for Node.js development and Azure Functions.
  5. Azure Functions SDK and QR Code Library: Install the Azure Functions SDK and the QR Code library by adding the following dependencies to your project.
    # Install Azure Functions SDK
    npm install @azure/functions
    
    # Install QR Code library
    npm install qrcode
    

Step 1. Setting Up the Project Create a new Azure Functions project using Visual Studio Code or your preferred development environment.

Initialize the project with the necessary configurations by creating the host.json and local.settings.json files. These files define the runtime behavior and local settings for your function.

host.json

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.*, 4.0.0)"
  }
}

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "YOUR_STORAGE_CONNECTION_STRING",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "AzureWebJobsFeatureFlags": "EnableWorkerIndexing"
  }
}

Step 2. Implementing the HTTP Trigger Create a new JavaScript file, e.g., index.js, and define your HTTP trigger function. In this case, I created a function that generates a QR code from the request body.

index.js

const { app } = require("@azure/functions");
const qr = require("qrcode");

app.http("QR-Generation", {
  methods: ["POST"],
  authLevel: "anonymous",
  handler: async (request, context) => {
    console.log("QR Code Generation function processed a request.");
    const data = await request.text();
    const parsedData = JSON.parse(data);
    const requestText = parsedData.data;
    if (!requestText) {
      return {
        status: 400,
        body: "Please provide data to be encoded in the QR code.",
      };
    }
    try {
      const qrCodeDataUrl = await qr.toDataURL(requestText);
      return {
        status: 200,
        body: qrCodeDataUrl,
        headers: {
          "Content-Type": "image/png",
        },
      };
    } catch (error) {
      context.res = {
        status: 500,
        body: `Error generating QR code: ${error.message}`,
      };
    }
  },
});

Step 3. Understanding the Code The HTTP trigger function takes a POST request with a JSON body containing a 'data' field. It uses the 'qr-code' library to generate a QR code in PNG format and returns it as the response.

Step 4. Testing the Function Locally Run your function locally using the Azure Functions Core Tools or the integrated Visual Studio Code debugger. Send a POST request to your function with a JSON body containing the 'data' field to test the QR code generation.

The code has been finalized. Please execute it by pressing F5.

Func-start Command Prompt

Begin by executing the function, followed by constructing a POST request for our endpoint.

QR- generation

Confirm that the function app has successfully received and executed your POST request at the specified endpoint. Once executed, retrieve the image URL response.

Executed

Please utilize the HTML tag and insert the source image URL.

<img src="image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIQAAACECAYAAABRRIOnAAAAAklEQVR4AewaftIAAAOZSURBVO3BQY5jiRUDwcwH3f/KdC+84OoDglQ10zYjzB/M/NcxU46ZcsyUY6YcM+WYKcdMOWbKMVOOmXLMlGOmHDPlmCnHTHnxIZXflISm0pLQVJ4koam0JHxC5Tcl4RPHTDlmyjFTXnxZEr5J5RNJaCpN5RMqLQlPkvBNKt90zJRjphwz5cUPU3lHEr5JpSWhqfyTVN6RhJ90zJRjphwz5cVfLglNpSWhqbQkNJX/Z8dMOWbKMVNe/OVU3pGEpvJEpSXhf9kxU46ZcsyUFz8sCT8pCU3lE0n4TUn4NzlmyjFTjpny4stUfpNKS0JTaUl4h0pLwidU/s2OmXLMlGOmmD/4P6LSktBUWhKaypMk/M2OmXLMlGOmmD/4gEpLwhOVn5SEb1JpSWgqT5LwRKUloam8IwmfOGbKMVOOmfLih6m8IwnvUGkqLQlNpSWhqTxRaUloKk9Unqi0JPymY6YcM+WYKS8+lIR3JKGpNJV3JOGJSktCU3mShKbSVFoSmkpLwhOVd6i0JHzimCnHTDlmyotfptKS0FRaEp6otCQ8UXmShKbSkvBNKk9UWhJ+0jFTjplyzJQXH1J5koSm0lRaEprKNyWhqTxJQlNpSfhEEppKS8JvOmbKMVOOmWL+4AMqT5LQVN6RhKbSkvCTVD6RhCcq70jCTzpmyjFTjpny4oeptCQ0lZaEptKS0FRaEprKO5LwiSQ0lZaEloSm8kTlSRI+ccyUY6YcM+XFlyXhico7kvAkCU3lHUn4RBKeJOGJyjuS0FS+6Zgpx0w5ZsqLH6bSktBUnqg8ScI7kvBEpSWhqTSV36TSkvBNx0w5ZsoxU8wf/MVUWhKayjuS0FRaEppKS8I7VJ4koak8ScInjplyzJRjprz4kMpvSsITlZaEptKS8A6Vd6i0JDxJwpMkNJVvOmbKMVOOmfLiy5LwTSrvSEJTaUloKk+S0FTekYRvUmlJ+KZjphwz5ZgpL36YyjuS8E9KwidUPqHSkvBEpSXhE8dMOWbKMVNe/I9ReUcSnqi0JDSVdyShqfybHDPlmCnHTHnxl0tCU3mHSkvCE5WWhKbSktBU/s2OmXLMlGOmvPhhSfhNSWgqT5LwjiQ8SUJTaUl4h8pvOmbKMVOOmfLiy1R+k8qTJDxReYfKkyQ8UXlHEp6ofNMxU46ZcswU8wcz/3XMlGOmHDPlmCnHTDlmyjFTjplyzJRjphwz5Zgpx0w5ZsoxU/4DRDGKOcke8wsAAAAASUVORK5CYII=" alt="QR-codeImage">

Conclusion

Congratulations! You have successfully crafted an Azure HTTP Trigger Function using Node.js to generate QR codes in response to POST requests. Take the next step by deploying this function to Azure, making it accessible over the internet, and seamlessly integrating it into your applications. Azure Functions provides a powerful, flexible, and scalable solution for serverless computing, allowing you to concentrate on crafting functionality without the burden of managing intricate infrastructure. Explore additional Azure services and features to enhance and tailor your serverless solutions to meet your specific needs. If you have any questions or insights to share, feel free to engage in the comments section below. Happy coding!