Skip to main content

Command Palette

Search for a command to run...

Writing and Deploying a Basic Azure Function in Python/Node.js with HTTP Trigger

Published
3 min read

Introduction

Azure Functions is a serverless computing service that enables developers to run code on-demand without provisioning or managing infrastructure. In this guide, we'll walk you through creating a simple Azure Function in Python or Node.js that responds to an HTTP trigger. You will learn how to deploy it using the Azure portal.

Step 1: Set Up Your Environment

Before you begin, make sure you have:

  1. An active Azure account (if not, you can create one here).

  2. Azure Functions Core Tools installed (for local testing).

  3. Azure CLI (for deployments).

Step 2: Create the Azure Function App

  1. Log into the Azure portal.

  2. Navigate to Create a resource > Function App.

  3. Fill out the necessary details:

    • Subscription: Select your subscription.

    • Resource Group: Create or use an existing one.

    • Function App Name: Choose a globally unique name.

    • Runtime Stack: Select either Python or Node.js.

    • Region: Choose a nearby location.

  4. Hosting: Choose the hosting options (default or as per requirement).

  5. Review + Create: Validate and click Create.

Step 3: Write the Code (Python or Node.js)

Python:

  1. In your local machine, create a folder for the project and navigate to it.

  2. Run the following command to initialize the project:

func init --worker-runtime python
  1. Create an HTTP trigger function:
func new --template "HTTP trigger" --name HttpTrigger
  1. This will generate a basic Python function in HttpTrigger/__init__.py. Update the code to respond with a custom message:
import logging

import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}!")
    else:
        return func.HttpResponse(
             "Please pass a name in the query string or in the request body",
             status_code=400
        )

Node.js:

  1. Initialize the project in the local directory:
func init --worker-runtime node
  1. Create a new HTTP trigger function:
func new --template "HTTP trigger" --name HttpTrigger
  1. In the HttpTrigger/index.js file, add the following code:
module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? "Hello, " + name + "."
        : "Please pass a name in the query string or in the request body";

    context.res = {
        // status: 200, /* Defaults to 200 */
        body: responseMessage
    };
};

Step 4: Test the Function Locally

  1. To test the function locally, run:
func start
  1. Once the function is running, you can test it by sending an HTTP request to http://localhost:7071/api/HttpTrigger?name=Azure.

Step 5: Deploy to Azure

  1. Log in to your Azure account using the CLI:
az login
  1. Navigate to your project directory and deploy the function using:
func azure functionapp publish <YourFunctionAppName>
  1. After deployment, you will receive a URL for your function. You can test it by navigating to:
https://<YourFunctionAppName>.azurewebsites.net/api/HttpTrigger?name=YourName

Step 6: Monitor and Scale

Azure provides a variety of monitoring tools, including Application Insights, which allow you to monitor logs, requests, and performance. You can also easily scale your function app based on demand.


Conclusion

You've successfully created and deployed a basic Azure Function with an HTTP trigger using either Python or Node.js. Azure Functions makes it easy to run serverless applications, reducing the need to manage servers or infrastructure. Keep exploring more powerful scenarios with Azure Functions!


More from this blog

Amazon S3 Storage Classes

43 posts