Add an API to Azure Static Web Apps with Azure Functions

You can add serverless APIs to Azure Static Web Apps that are powered by Azure Functions. This article demonstrates how to add and deploy an API to an Azure Static Web Apps site.

Note

The functions provided by default in Static Web Apps are pre-configured to provide secure API endpoints and only support HTTP-triggered functions. See API support with Azure Functions for information on how they differ from standalone Azure Functions apps.

Prerequisites

Tip

You can use the nvm tool to manage multiple versions of Node.js on your development system. On Windows, NVM for Windows can be installed via Winget.

Create the static web app

Before adding an API, create and deploy a frontend application to Azure Static Web Apps by following the Building your first static site with Azure Static Web Apps quickstart.

Once you have a frontend application deployed to Azure Static Web Apps, clone your app repository. For example, to clone using the git command line:

git clone https://github.com/my-username/my-first-static-web-app

In Visual Studio Code, open the root of your app's repository. The folder structure contains the source for your frontend app and the Static Web Apps GitHub workflow in .github/workflows folder.

├── .github
│   └── workflows
│       └── azure-static-web-apps-<DEFAULT_HOSTNAME>.yml
│
└── (folders and files from your static web app)

Create the API

You create an Azure Functions project for your static web app's API. By default, the Static Web Apps Visual Studio Code extension creates the project in a folder named api at the root of your repository.

  1. Press F1 to open the Command Palette.

  2. Select Azure Static Web Apps: Create HTTP Function.... If you're prompted to install the Azure Functions extension, install it and rerun this command.

  3. When prompted, enter the following values:

    Prompt Value
    Select a language JavaScript
    Select a programming model V3
    Provide a function name message

    Tip

    You can learn more about the differences between programming models in the Azure Functions developer guide

    An Azure Functions project is generated with an HTTP triggered function. Your app now has a project structure similar to the following example.

    ├── .github
    │   └── workflows
    │       └── azure-static-web-apps-<DEFAULT_HOSTNAME>.yml
    │
    ├── api
    │   ├── message
    │   │   ├── function.json
    │   │   └── index.js
    │   ├── host.json
    │   ├── local.settings.json
    │   └── package.json
    │
    └── (folders and files from your static web app)
    
  4. Next, change the message function to return a message to the frontend. Update the function in api/message/index.js with the following code.

    module.exports = async function (context, req) {
        context.res.json({
            text: "Hello from the API"
        });
    };
    

Tip

You can add more API functions by running the Azure Static Web Apps: Create HTTP Function... command again.

Update the frontend app to call the API

Update your frontend app to call the API at /api/message and display the response message.

If you used the quickstarts to create the app, use the following instructions to apply the updates.

Update the content of the src/index.html file with the following code to fetch the text from the API function and display it on the screen.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Vanilla JavaScript App</title>
</head>

<body>
    <main>
    <h1>Vanilla JavaScript App</h1>
    <p>Loading content from the API: <b id="name">...</b></p>
    </main>

    <script>
    (async function() {
        const { text } = await( await fetch(`/api/message`)).json();
        document.querySelector('#name').textContent = text;
    }());
    </script>
</body>

</html>

Run the frontend and API locally

To run your frontend app and API together locally, Azure Static Web Apps provides a CLI that emulates the cloud environment. The CLI uses the Azure Functions Core Tools to run the API.

Install command line tools

Ensure you have the necessary command line tools installed.

npm install -g @azure/static-web-apps-cli

Tip

If you don't want to install the swa command line globally, you can use npx swa instead of swa in the following instructions.

Build frontend app

If your app uses a framework, build the app to generate the output before running the Static Web Apps CLI.

There's no need to build the app.

Run the application locally

Run the frontend app and API together by starting the app with the Static Web Apps CLI. Running the two parts of your application this way allows the CLI to serve your frontend's build output from a folder, and makes the API accessible to the running app.

  1. In root of your repository, start the Static Web Apps CLI with the start command. Adjust the arguments if your app has a different folder structure.

    Pass the current folder (src) and the API folder (api) to the CLI.

    swa start src --api-location api
    
  2. Windows Firewall may prompt to request that the Azure Functions runtime can access the Internet. Select Allow.

  3. When the CLI processes start, access your app at http://localhost:4280/. Notice how the page calls the API and displays its output, Hello from the API.

  4. To stop the CLI, type Ctrl + C.

Add API location to workflow

Before you can deploy your app to Azure, update your repository's GitHub Actions workflow with the correct location of your API folder.

  1. Open your workflow at .github/workflows/azure-static-web-apps-<DEFAULT-HOSTNAME>.yml.

  2. Search for the property api_location and set the value to api.

    ###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
    # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
    app_location: "/" # App source code path
    api_location: "api" # Api source code path - optional
    output_location: "build" # Built app content directory - optional
    ###### End of Repository/Build Configurations ######
    
  3. Save the file.

Deploy changes

To publish changes to your static web app in Azure, commit and push your code to the remote GitHub repository.

  1. Press F1 to open the Command Palette.

  2. Select the Git: Commit All command.

  3. When prompted for a commit message, enter feat: add API and commit all changes to your local git repository.

  4. Press F1 to open the Command Palette.

  5. Select the Git: push command.

    Your changes are pushed to the remote repository in GitHub, triggering the Static Web Apps GitHub Actions workflow to build and deploy your app.

  6. Open your repository in GitHub to monitor the status of your workflow run.

  7. When the workflow run completes, visit your static web app to view your changes.

Next steps