title | description | services | author | ms.service | ms.topic | ms.date | ms.author | ms.custom |
---|---|---|---|---|---|---|---|---|
Add an API to Azure Static Web Apps with Azure Functions |
Get started with Azure Static Web Apps by adding a Serverless API to your static web app using Azure Functions. |
static-web-apps |
manekinekko |
static-web-apps |
how-to |
12/03/2021 |
wachegha |
devx-track-js |
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.
- Azure account with an active subscription.
- If you don't have an account, you can create one for free.
- Visual Studio Code
- Azure Static Web Apps extension for Visual Studio Code
- Azure Functions extension for Visual Studio Code
- Node.js to run the frontend app and API
Before adding an API, create and deploy a frontend application to Azure Static Web Apps. Use an existing app that you have already deployed or create one by following the Building your first static site with Azure Static Web Apps quickstart.
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)
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.
-
Press F1 to open the Command Palette.
-
Select Azure Static Web Apps: Create HTTP Function.... If you're prompted to install the Azure Functions extension, install it and re-run this command.
-
When prompted, enter the following values:
Prompt Value Select a language JavaScript Provide a function name message 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)
-
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 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>
-
Update the content of src/app/app.module.ts with the following code to enable
HttpClient
in your app.import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from "./app.component"; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule], bootstrap: [AppComponent] }) export class AppModule {}
-
Update the content of src/app/app.component.ts with the following code to fetch the text from the API function and display it on the screen.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<div>{{message}}</div>`, }) export class AppComponent { message = ''; constructor(private http: HttpClient) { this.http.get('/api/message') .subscribe((resp: any) => this.message = resp.text); } }
Update the content of src/App.js with the following code to fetch the text from the API function and display it on the screen.
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState('');
useEffect(() => {
(async function () {
const { text } = await( await fetch(`/api/message`)).json();
setData(text);
})();
});
return <div>{data}</div>;
}
export default App;
Update the content of src/App.vue with the following code to fetch the text from the API function and display it on the screen.
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
name: "App",
data() {
return {
message: ""
};
},
async mounted() {
const { text } = await (await fetch("/api/message")).json();
this.message = text;
}
};
</script>
To run your frontend app and API together locally, Azure Static Web Apps provides a CLI that emulates the cloud environment. The CLI leverages the Azure Functions Core Tools to run the API.
Ensure you have the necessary command line tools installed.
-
Install Azure Static Web Apps CLI.
npm install -g @azure/static-web-apps-cli
-
Install Azure Functions Core Tools V3.
npm install -g azure-functions-core-tools@3
If your app uses a framework, build the app to generate the output before running the Static Web Apps CLI.
There is no need to build the app.
Build the app into the dist/angular-basic folder.
npm run build --prod
Build the app into the build folder.
npm run build
Build the app into the dist folder.
npm run build
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.
-
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
Pass the build output folder (
dist/angular-basic
) and the API folder (api
) to the CLI.swa start dist/angular-basic --api-location api
Pass the build output folder (
build
) and the API folder (api
) to the CLI.swa start build --api-location api
Pass the build output folder (
dist
) and the API folder (api
) to the CLI.swa start dist --api-location api
-
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
. -
To stop the CLI, type Ctrl + C.
Before you can deploy your app to Azure, update your repository's GitHub Actions workflow with the correct location of your API folder.
-
Open your workflow at .github/workflows/azure-static-web-apps-<DEFAULT-HOSTNAME>.yml.
-
Search for the property
api_location
and set the value toapi
. -
Save the file.
To publish changes to your static web app in Azure, commit and push your code to the remote GitHub repository.
-
Press F1 to open the Command Palette.
-
Select the Git: Commit All command.
-
When prompted for a commit message, enter add API and commit all changes to your local git repository.
-
Press F1 to open the Command Palette.
-
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.
-
Open your repository in GitHub to monitor the status of your workflow run.
-
When the workflow run completes, visit your static web app to view your changes.
[!div class="nextstepaction"] Configure app settings