GitHub - Azure-Samples/functions-quickstart-typescript-azd: This Quickstart uses Azure Developer command-line (azd) tools to create functions that respond to HTTP requests. After testing the code locally, you deploy it to a new serverless function app you create running in a Flex Consumption plan in Azure Functions. This follows current best practices for secure and scalable Azure Functions deployments (original) (raw)

Azure Functions TypeScript HTTP Trigger using Azure Developer CLI

This repository contains an Azure Functions HTTP trigger reference sample written in TypeScript and deployed to Azure using Azure Developer CLI (azd). The sample uses managed identity and a virtual network to make sure deployment is secure by default.

This source code supports the article Quickstart: Create and deploy functions to Azure Functions using the Azure Developer CLI.

Prerequisites

Initialize the local project

You can initialize a project from this azd template in one of these ways:

Prepare your local environment

Add a file named local.settings.json in the root of your project with the following contents:

{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "node" } }

Run your app from the terminal

  1. Run these commands in the virtual environment:
  2. From your HTTP test tool in a new terminal (or from your browser), call the HTTP GET endpoint: http://localhost:7071/api/httpget
  3. Test the HTTP POST trigger with a payload using your favorite secure HTTP test tool. This example uses the curl tool with payload data from the testdata.json project file:
    curl -i http://localhost:7071/api/httppost -H "Content-Type: text/json" -d "@src/functions/testdata.json"
  4. When you're done, press Ctrl+C in the terminal window to stop the func.exe host process.

Run your app using Visual Studio Code

  1. Open the root folder in a new terminal.
  2. Run the code . code command to open the project in Visual Studio Code.
  3. Press Run/Debug (F5) to run in the debugger. Select Debug anyway if prompted about local emulator not running.
  4. Send GET and POST requests to the httpget and httppost endpoints respectively using your HTTP test tool (or browser for httpget). If you have the RestClient extension installed, you can execute requests directly from the test.http project file.

Source Code

The source code for the GET and POST functions is in the httpGetFunction.ts and httpPostBodyFunction.ts code files, respectively. Azure Functions requires the use of the @azure/functions library.

This code shows an HTTP GET triggered function:

export async function httpGetFunction(request: HttpRequest, context: InvocationContext): Promise { context.log(Http function processed request for url "${request.url}");

const name = request.query.get('name') || await request.text() || 'world';

return { body: `Hello, ${name}!` };

};

This code shows an HTTP POST triggered function that expects person object with name and age values in the request body.

export async function httpPostBodyFunction(request: HttpRequest, context: InvocationContext): Promise { context.log(Http function processed request for url "${request.url}");

    try {
        const data: any  = await request.json();

        if (!isPerson(data)) {
            return {
                status: 400,
                body: 'Please provide both name and age in the request body.'
            };
        }

        return {
            status: 200,
            body: `Hello, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>d</mi><mi>a</mi><mi>t</mi><mi>a</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mo stretchy="false">!</mo><mi>Y</mi><mi>o</mi><mi>u</mi><mi>a</mi><mi>r</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{data.name}! You are </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">d</span><span class="mord mathnormal">a</span><span class="mord mathnormal">t</span><span class="mord mathnormal">a</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mclose">!</span><span class="mord mathnormal" style="margin-right:0.22222em;">Y</span><span class="mord mathnormal">o</span><span class="mord mathnormal">u</span><span class="mord mathnormal">a</span><span class="mord mathnormal">re</span></span></span></span>{data.age} years old.`
        };
    } catch (error) {
        return {
            status: 400,
            body: 'Invalid request body. Please provide a valid JSON object with name and age.'
        };
    }

};

Deploy to Azure

Run this command to provision the function app, with any required Azure resources, and deploy your code:

By default, this sample prompts to enable a virtual network for enhanced security. If you want to deploy without a virtual network without prompting, you can configure VNET_ENABLED to false before running azd up:

azd env set VNET_ENABLED false azd up

You're prompted to supply these required deployment parameters:

Parameter Description
Environment name An environment that's used to maintain a unique deployment context for your app. You won't be prompted if you created the local project using azd init.
Azure subscription Subscription in which your resources are created.
Azure location Azure region in which to create the resource group that contains the new Azure resources. Only regions that currently support the Flex Consumption plan are shown.

After publish completes successfully, azd provides you with the URL endpoints of your new functions, but without the function key values required to access the endpoints. To learn how to obtain these same endpoints along with the required function keys, see Invoke the function on Azure in the companion article Quickstart: Create and deploy functions to Azure Functions using the Azure Developer CLI.

Redeploy your code

You can run the azd up command as many times as you need to both provision your Azure resources and deploy code updates to your function app.

[!NOTE] Deployed code files are always overwritten by the latest deployment package.

Clean up resources

When you're done working with your function app and related resources, you can use this command to delete the function app and its related resources from Azure and avoid incurring any further costs:

```shell azd down