Add an API to Azure Static Web Apps Preview with Azure Functions

You can add serverless APIs to Azure Static Web Apps via integration with Azure Functions. This article demonstrates how to add and deploy an API to an Azure Static Web Apps site.

Prerequisites

Create a Git repository

The following steps demonstrate how to create a new repository and clone the files to your computer.

  1. Make sure you are logged in to GitHub and, navigate to https://github.com/staticwebdev/vanilla-basic/generate to create a new repository.

  2. In the Repository name box, enter my-vanilla-api.

  3. Click Create repository from template.

    Create a new repository from vanilla-basic

Once your project is created, copy the URL in your browser for the new repository. You use this URL in Visual Studio Code to clone the Git repository.

  1. Press F1 to open command in the Command Palette.

  2. Paste the URL into the Git: Clone prompt, and press Enter.

    Clone a GitHub project using Visual Studio Code

    Follow the prompts to select a repository location to clone the project.

Create the API

Next, you create an Azure Functions project as the application's API.

  1. Inside the my-vanilla-api project, create a sub-folder named api.

  2. Press F1 to open the Command Palette

  3. Type Azure Functions: Create New Project...

  4. Press Enter

  5. Choose Browse

  6. Select the api folder as the directory for your project workspace

  7. Choose Select

    Screenshot shows the A P I folder and the Select button.

  8. Provide the following information at the prompts:

    • Select a language: Choose JavaScript
    • Select a template for your project's first function: Choose HTTP trigger
    • Provide a function name: Enter GetMessage
    • Authorization level: Choose Anonymous, which enables anyone to call your function endpoint.

Visual Studio Code generates an Azure Functions project with an HTTP triggered function.

Your app now has a project structure similar to the following example.

├── api
│   ├── GetMessage
│   │   ├── function.json
│   │   ├── index.js
│   │   └── sample.dat
│   ├── host.json
│   ├── local.settings.json
│   ├── package.json
│   └── proxies.json
├── index.html
├── readme.md
└── styles.css

Next, you'll change the GetMessage function to return a message to the front-end.

  1. Update the GetMessage function under api/GetMessage/index.js with the following code.

    module.exports = async function (context, req) {
      context.res = {
        body: {
          text: "Hello from the API"
        }
      };
    };
    
  2. Update the GetMessage configuration under api/GetMessage/function.json with the following settings.

    {
      "bindings": [
        {
          "authLevel": "anonymous",
          "type": "httpTrigger",
          "direction": "in",
          "name": "req",
          "methods": [
            "get"
          ],
          "route": "message"
        },
        {
          "type": "http",
          "direction": "out",
          "name": "res"
        }
      ]
    }
    

With the above settings, the API endpoint is:

  • Triggered when an HTTP request is made to the function
  • Available to all requests regardless of authentication status
  • Exposed via the /api/message route

Run the API locally

Visual Studio Code integrates with Azure Functions Core Tools to let you run this project on your local development computer before you publish to Azure.

Tip

Make sure you have all the resources listed in the prerequisites section installed before proceeding.

  1. Run the function by pressing F5 to start the Functions app.

  2. If Azure Functions Core Tools isn't already installed, select Install at the prompt.

    The Core Tools shows output from the running application in the Terminal panel. As a part of the output, you can see the URL endpoint of your HTTP-triggered function running locally.

    Screenshot shows the TERMINAL tab where you can see the U R L.

  3. With Core Tools running, navigate to the following URL to verify the API is running correctly: http://localhost:7071/api/message.

    The response in the browser should look similar to the following example:

    Alt textScreenshot shows a text response in a browser.

  4. Press Shift + F5 to stop the debugging session.

Call the API from the application

When deployed to Azure, requests to the API are automatically routed to the Functions app for requests sent to the api route. Working locally, you have to configure the application settings to proxy requests to the local API.

Local proxy

You can configure a proxy for the Live Server Visual Studio Code extension that routes all requests to /api to the running API endpoint at http://127.0.0.1:7071/api.

  1. Open the .vscode/settings.json file.

  2. Add the following settings to specify a proxy for Live Server.

    "liveServer.settings.proxy": {
       "enable": true,
       "baseUri": "/api",
       "proxyUri": "http://127.0.0.1:7071/api"
    }
    

    This configuration is best saved in project settings file, as opposed to in the user settings file.

    Using project settings assures the proxy isn't applied to all other projects opened in Visual Studio Code.

Update HTML files to access the API

  1. Next, update the content of the 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() {
          let { text } = await( await fetch(`/api/message`)).json();
          document.querySelector('#name').textContent = text;
        }())
      </script>
    </body>
    
    </html>
    
  2. Press F5 to start the API project.

  3. Press F1 and choose Live Server: Open with Live Server.

    You should now see the API message in the web page.

    Screenshot shows the A P I message in a browser.

    Note

    You can use other HTTP servers or proxies to serve the index.html file. Accessing the index.html from file:/// will not work.

  4. Press Shift + F5 to stop the API project.

Commit and push your changes to GitHub

Using Visual Studio Code, commit and push your changes to the remote git repository.

  1. Press F1 to open the Command Palette
  2. Type Git: Commit All
  3. Add a commit message and press Enter
  4. Press F1
  5. Type in Git: push and press Enter

Create a static web app

  1. Navigate to the Azure portal
  2. Click Create a Resource
  3. Search for Static Web App
  4. Click Static Web App (Preview)
  5. Click Create

Next, add the app-specific settings.

  1. Select your Azure subscription
  2. Select or create a new Resource Group
  3. Name the app my-vanilla-api.
  4. Select Region closest to you
  5. Select the Free SKU
  6. Click the Sign-in with GitHub button and authenticate with GitHub
  7. Select your preferred Organization
  8. Select my-vanilla-api from the Repository drop-down
  9. Select master from the Branch drop-down
  10. Select the framework of your choice for build configuration from the Build Presets drop-down

These fields will reflect the app type's default project structure. Change the values to suit your app.

Next, add the following build details.

  1. Enter / for the App location.

  2. Enter api in the Api location box.

  3. Clear the default value out of the App artifact location, leaving the box empty.

  4. Click Review + create.

  5. Click the Create button

    Once you click the Create button, Azure does two things. First, the underlying cloud services are created to support the app. Next, a background process begins to build and deploy the application.

  6. Click the Go to Resource button to take you to the web app's Overview page.

    As the app is being built in the background, you can click on the banner which contains a link to view the build status.

    GitHub Workflow

  7. Once the deployment is complete, ou can navigate to the web app, by clicking on the URL link shown on the Overview page.

    Access static app URL from the Azure portal

Clean up resources

If you don't want to keep this application for further use, you can use the following steps to delete the Azure Static Web App and its related resources.

  1. Navigate to the Azure portal
  2. In the top search bar, type Resource groups
  3. Click Resource groups
  4. Select myResourceGroup
  5. On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.
  6. Select Delete
  7. Type myResourceGroup in the text box
  8. Select Delete.

Next steps