4. Add APIs to function app and redeploy to Azure

In this article of the series, you add APIs to add and delete resource groups, then redeploy your Azure Function app in Visual Studio Code.

At this point in the article series, you created a local function app with one API to list your subscription's resource groups and you deployed that app to Azure. As an Azure developer, you may want to create or delete resource groups as part of your process automation pipeline.

Create resource-group API for your function app

Use the Visual Studio Code extension for Azure Functions to add the APIs files to your function app.

  1. Open the Visual Studio Code command palette: Ctrl + Shift + p.

  2. Enter Azure Functions: Create Function then press enter to begin the process.

  3. Use the following table to create the /api/resource-group API:

    Prompt Value
    Select a template for your function HTTP trigger
    Provide a function name resource-group
    Authorization level Select anonymous. If you continue with this project after this article series, change the authorization level to the function. Learn more about Function-level authorization.
  4. To limit the function to adding and deleting resource groups, open the ./resource-group/function.json and edit the methods to POST and DELETE.

    {
      "bindings": [
        {
          "authLevel": "anonymous",
          "type": "httpTrigger",
          "direction": "in",
          "name": "req",
          "methods": [
            "post", "delete"
          ]
        },
        {
          "type": "http",
          "direction": "out",
          "name": "res"
        }
      ],
      "scriptFile": "../dist/resource-group/index.js"
    }
    

Add TypeScript code to add and delete resource groups

  1. Open the ./resource-group/index.ts file and replace the contents with the following:

    import { AzureFunction, Context, HttpRequest } from "@azure/functions";
    import {
      createResourceGroup,
      deleteResourceGroup,
    } from "../lib/azure-resource-groups";
    
    /*
    
    Add Resource Group:
    
    curl -X POST http://localhost:7071/api/resource-group \
      -H 'Content-Type: application/json' \
      -d '{"resourceGroupName":"REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME","resourceGroupLocation":"westus"}'
    
    curl -X DELETE http://localhost:7071/api/resource-group \
      -H 'Content-Type: application/json' \
      -d '{"resourceGroupName":"REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME"}'
    
    */
    const httpTrigger: AzureFunction = async function (
      context: Context,
      req: HttpRequest
    ): Promise<void> {
      try {
        const name: string = req?.body?.resourceGroupName;
        const location: string = req?.body?.resourceGroupLocation;
        const tags: {
          [propertyName: string]: string;
        } = req.body.resourceGroupTags;
    
        switch (req.method) {
          case "POST":
            if (!req.body.resourceGroupName || !req.body.resourceGroupLocation) {
              const errorMessage = "Missing required parameters in POST body.";
    
              context.res = {
                status: 400,
                body: {
                  errorMessage,
                },
              };
            } else {
              const result = await createResourceGroup(name, location, tags);
              context.res = {
                body: {
                  status: 200,
                },
              };
            }
    
            break;
          case "DELETE":
            if (!req.body.resourceGroupName) {
              const errorMessage = "Missing required parameter in DELETE body.";
    
              context.res = {
                status: 400,
                body: {
                  errorMessage,
                },
              };
            } else {
              const result = await deleteResourceGroup(name);
              context.res = {
                body: {
                  status: 200,
                },
              };
            }
            break;
          default:
            throw new Error("Method not supported");
        }
      } catch (err) {
        context.res = {
          status: 500,
          body: err,
        };
      }
    };
    
    export default httpTrigger;
    

    This file depends on new functionality in the ./lib directory.

  2. Copy the following code into the bottom of the azure-resource-groups.ts file:

    export const createResourceGroup = async (resourceGroupName: string, location: string, tags: { [propertyName: string]: string; }) =>{
    
        const resourceGroupParameters = {
            location: location,
            tags: tags
        };
    
        return await resourceManagement.resourceGroups.createOrUpdate(
            resourceGroupName,
            resourceGroupParameters
        );
    }
    export const deleteResourceGroup = async (resourceGroupName: string) =>{
        return await resourceManagement.resourceGroups.deleteMethod(resourceGroupName);
    }
    

Start your local function app and test the new API

  1. In the Visual Studio Code integrated terminal, run the local project:

    npm start
    
  2. Wait until the integrated bash terminal displays the running function's URL.

    Partial screenshot of Visual Studio Code's integrated bash terminal when the Azure Function is running locally and displaying the local URLs for the APIs in the Function app.

  3. Use the following curl command in a different integrated bash terminal, to call your API, to add a resource group to your subscription. Change the name of the resource group to use your own naming conventions.

    curl -X POST http://localhost:7071/api/resource-group \
      -H 'Content-Type: application/json' \
      -d '{"resourceGroupName":"REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME","resourceGroupLocation":"westus"}'
    
  4. Use the following curl command to see the new resource group listed in your subscription.

    curl http://localhost:7071/api/resource-groups
    
  5. Use the following curl command to delete the resource group you just added.

    curl -X DELETE http://localhost:7071/api/resource-group \
      -H 'Content-Type: application/json' \
      -d '{"resourceGroupName":"REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME"}'
    

Redeploy your function app with new APIs to Azure

  1. In VS Code, select the Azure logo to open the Azure Explorer, then under Functions, select the blue up arrow to deploy your app:

    Deploy to Azure Functions command

    Alternately, you can deploy by opening the Command Palette with Ctrl + Shift + p, entering deploy to function app, and running the Azure Functions: Deploy to Function App command.

  2. Select your function app from the list of apps.

  3. Select Deploy from the pop-up window.

  4. Wait until the deployment completes.

Verify Function APIs with browser

In the following cURL commands, replace YOUR-RESOURCE-NAME with your Azure Function resource name and REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME with your resource group name.

  1. Use the following curl command in an integrated bash terminal, to call to add a resource group to your subscription. Change the name of the resource and resource group to use your own naming conventions.

    curl -X POST https://YOUR-RESOURCE_NAME.azurewebsites.net/api/resource-group \
      -H 'Content-Type: application/json' \
      -d '{"resourceGroupName":"REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME","resourceGroupLocation":"westus"}'
    
  2. Use the following curl command to see the new resource group listed in your subscription.

    curl https://YOUR-RESOURCE_NAME.azurewebsites.net/api/resource-groups
    
  3. Use the following curl command to delete the resource group you just added.

    curl -X DELETE https://YOUR-RESOURCE_NAME.azurewebsites.net/api/resource-group \
      -H 'Content-Type: application/json' \
      -d '{"resourceGroupName":"REPLACE-WITH-YOUR-RESOURCE-GROUP-NAME"}'
    

    Deleting a resource group will delete all resources within the group and may take a minute to complete.

Next steps