Skip to content

Commit a8e1484

Browse files
authored
Merge pull request #111316 from manekinekko/wachegha-api-functions
Add API to Azure Static Apps using Azure Functions
2 parents 32a53ca + 589bef3 commit a8e1484

16 files changed

+254
-36
lines changed

articles/static-apps/add-api.md

Lines changed: 254 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,277 @@
11
---
2-
title: Add an API to App Service Static Apps with Azure Functions
3-
description: #Required; article description that is displayed in search results.
4-
services: #Required for articles that deal with a service; service slug assigned to your service by ACOM.
2+
title: Add an API to Azure Static Web Apps with Azure Functions
3+
description: Get started with Azure Static Web Apps by adding a Serverless API to your static web app using Azure Functions.
4+
services: azure-functions
55
author: manekinekko
66
ms.service: azure-functions
77
ms.topic: how-to
88
ms.date: 05/08/2020
99
ms.author: wachegha
1010
---
1111

12-
<!---Recommended: Removal all the comments in this template before you sign-off or merge to master.--->
12+
# Add an API to Azure Static Web Apps with Azure Functions
1313

14-
# Add an API to App Service Static Apps with Azure Functions
14+
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.
1515

16-
Introductory paragraph.
16+
## Prerequisites
1717

18-
<!---Required:
19-
Lead with a light intro that describes, in customer-friendly language, what the customer will learn, or do, or accomplish. Answer the fundamental "why would I want to do this?" question.
20-
--->
18+
- Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free).
19+
- [Visual Studio Code](https://code.visualstudio.com/)
20+
- [Azure Functions extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions) for Visual Studio Code
21+
- [Live Server Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) extension.
2122

22-
<!---Avoid notes, tips, and important boxes. Readers tend to skip over them. Better to put that info directly into the article text.--->
23+
## Create a git repository
2324

24-
## Prerequisites
25+
The following steps demonstrate how to create a new repository and clone the files to your computer.
2526

26-
- First prerequisite
27-
- Second prerequisite
28-
- Third prerequisite
29-
<!--- Make Prerequisites your first H2 if you have them.
30-
If there's something a customer needs to take care of before they start (for example, creating a VM) it's OK to link to that content before they begin.
31-
--->
27+
1. Navigate to https://github.com/staticwebdev/vanilla-basic/generate to create a new repository
28+
1. In the _Repository name_ box, enter **my-vanilla-api**
29+
1. Click **Create repository from template**
3230

33-
## <section>
31+
:::image type="content" source="media/add-api/create-repository.png" alt-text="Create a new repository from vanilla-basic":::
3432

35-
<!---Detail what the reader needs to know in each section
36-
--->
33+
Once your project is created, you can use Visual Studio Code to clone the Git repository.
3734

38-
Include a sentence or two to explain only what is needed to complete the procedure.
35+
1. Press **F1** to open command in the Command Palette.
36+
1. Paste the URL into the _Git: Clone_ prompt, and press **Enter**.
3937

40-
1. Step one of the procedure
41-
1. Step two of the procedure
42-
1. Step three of the procedure
43-
<!--- ![Browser](media/contribute-how-to-mvc-quickstart/browser.png) --->
44-
<!---Use screenshots but be judicious to maintain a reasonable length. Make sure screenshots align to the [current standards](contribute-mvc-screen-shots.md).
45-
If users access your product/service via a web browser the first screenshot should always include the full browser window in Chrome or Safari. This is to show users that the portal is browser-based - OS and browser agnostic.--->
46-
1. Step four of the procedure
38+
:::image type="content" source="media/add-api/vscode-git-0.png" alt-text="Clone a GitHub project using Visual Studio Code":::
4739

48-
## Next steps
40+
:::image type="content" source="media/add-api/github-clone-url.png" alt-text="Clone a GitHub project using Visual Studio Code":::
4941

50-
<!-- Uncomment this block and add the appropriate link
5142

52-
> [!div class="nextstepaction"]
53-
> [Next steps button](contribute-get-started-mvc.md)
43+
## Create your local project
44+
45+
In this section, you use Visual Studio Code to create a local Azure Functions project. Later, you publish the Functions app to Azure.
46+
47+
1. Inside the _my-vanilla-api_ project, create a sub-folder named **api**.
48+
49+
> [!NOTE]
50+
> You can give this folder any name. This example uses `api`
51+
52+
2. Press **F1** to open the Command Palette
53+
3. Type **Azure Functions: Create New Project...**
54+
4. Press **Enter**
55+
5. Choose **Browse**
56+
6. Select the **api** folder as the directory for your project workspace
57+
7. Choose **Select**
58+
59+
:::image type="content" source="media/add-api/create-azure-functions-vscode-1.png" alt-text="Create a new Azure Functions using Visual Studio Code":::
60+
61+
8. Provide the following information at the prompts:
62+
63+
- _Select a language for your function project_: Choose **JavaScript**
64+
- _Select a template for your project's first function_: Choose **HTTP trigger**
65+
- _Provide a function name_: Type **GetMessage**
66+
- _Authorization level_: Choose **Anonymous**, which enables anyone to call your function endpoint.
67+
- To learn about authorization levels, see [Authorization keys](../azure-functions/functions-bindings-http-webhook-trigger.md#authorization-keys).
68+
69+
9. Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger.
70+
- You can view the local project files in Visual Studio Code's explorer window.
71+
- To learn more about files that are created, see [Generated project files](https://docs.microsoft.com/azure/azure-functions/functions-develop-vs-code#generated-project-files).
72+
73+
10. Your app should now have a project structure similar to this example.
74+
75+
```files
76+
├── api
77+
│ ├── GetMessage
78+
│ │ ├── function.json
79+
│ │ ├── index.js
80+
│ │ └── sample.dat
81+
│ ├── host.json
82+
│ ├── local.settings.json
83+
│ ├── package.json
84+
│ └── proxies.json
85+
├── index.html
86+
├── readme.md
87+
└── styles.css
88+
```
89+
90+
11. Next, update the `GetMessage` function under _api/GetMessage/index.js_ with the following code.
91+
92+
```JavaScript
93+
module.exports = async function (context, req) {
94+
context.res = {
95+
body: {
96+
text: "Hello from the API"
97+
}
98+
};
99+
};
100+
```
101+
102+
12. Update the `GetMessage` configuration under `api/GetMessage/function.json` with the following settings.
103+
104+
```json
105+
{
106+
"bindings": [
107+
{
108+
"authLevel": "anonymous",
109+
"type": "httpTrigger",
110+
"direction": "in",
111+
"name": "req",
112+
"methods": [
113+
"get"
114+
],
115+
"route": "message"
116+
},
117+
{
118+
"type": "http",
119+
"direction": "out",
120+
"name": "res"
121+
}
122+
]
123+
}
124+
```
125+
With the above settings, the API endpoint is:
126+
127+
- Triggered with an HTTP request is made to the function
128+
- Available to all requests regardless of authentication status
129+
- Exposed via the _/api/message_ route
130+
## Run the function locally
131+
132+
Visual Studio Code integrates with [Azure Functions Core Tools](https://docs.microsoft.com/azure/azure-functions/functions-run-local) to let you run this project on your local development computer before you publish to Azure.
133+
134+
1. Run the function by pressing **F5** to start the Functions app, and the Core Tools output is displayed in the _Terminal_ panel.
135+
136+
2. If Azure Functions Core Tools isn't already installed, select **Install** at the prompt.
137+
138+
When the Core Tools are installed, your app starts in the _Terminal_ panel. As a part of the output, you can see the URL endpoint of your HTTP-triggered function running locally.
139+
140+
:::image type="content" source="media/add-api/create-azure-functions-vscode-2.png" alt-text="Create a new Azure Functions using Visual Studio Code":::
141+
142+
3. With Core Tools running, navigate to the following URL to execute a `GET` request.
143+
144+
<http://localhost:7071/api/message>
145+
146+
A response is returned, which looks like the following in the browser:
147+
148+
:::image type="content" source="media/add-api/create-azure-functions-vscode-3.png" alt-text="Create a new Azure Functions using Visual Studio Code":::
149+
150+
After you've verified that the function runs correctly, you can call the API from the JavaScript application.
151+
152+
### Call the API from the application
153+
154+
[!INCLUDE [static-web-apps-local-proxy](../../includes/static-web-apps-local-proxy.md)]
155+
156+
157+
#### Update files to access the API
158+
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:
54159

55-
-->
160+
```html
161+
<!DOCTYPE html>
162+
<html lang="en">
56163

57-
<!--- Required:
58-
A single link in the blue box format should direct the customer to the next article - and you can shorten the title in the boxes if the original one doesn't fit.
59-
--->
164+
<head>
165+
<meta charset="UTF-8">
166+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
167+
<link rel="stylesheet" href="styles.css">
168+
<title>Vanilla JavaScript App</title>
169+
</head>
170+
171+
<body>
172+
<main>
173+
<h1>Vanilla JavaScript App</h1>
174+
<p>Loading message from the API: <b id="name">...</b></p>
175+
</main>
176+
177+
<script>
178+
(async function() {
179+
let { text } = await( await fetch(`/api/message`)).json();
180+
document.querySelector('#name').textContent = text;
181+
}())
182+
</script>
183+
</body>
184+
185+
</html>
186+
```
187+
188+
With Core Tools running, use the [Live Server](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) Visual Studio Code extension to serve the _index.html_ file and open it a in browser.
189+
190+
2. Press **F1** and choose **Live Server: Open with Live Server**.
191+
192+
:::image type="content" source="media/add-api/create-azure-functions-vscode-4.png" alt-text="Create a new Azure Functions using Visual Studio Code":::
193+
194+
> [!NOTE]
195+
> You can use other HTTP servers or proxies to serve the `index.html` file. Accessing the `index.html` from `file:///` will not work.
196+
197+
### Commit and push your changes to GitHub
198+
199+
Using Visual Studio Code, commit and push your changes to the remote git repository.
200+
201+
1. Pressing **F1** to open the Command Palette
202+
1. Type **Git: Commit All**
203+
1. Add a commit message
204+
1. Type in **Git: push**
205+
206+
## Create a static web app
207+
208+
:::image type="content" source="media/add-api/create-static-app-on-azure-portal-1.png" alt-text="Create static app on the Azure portal - screen 1":::
209+
210+
1. Navigate to the [Azure portal](https://portal.azure.com)
211+
1. Type **Static Web Apps** in the top search bar
212+
1. Click on **Static Web Apps**
213+
1. Click **Add**
214+
1. Select your _Azure subscription_
215+
1. Select or create a new _Resource Group_
216+
1. Name the app **my-vanilla-api**.
217+
1. Select _Region_ closest to you
218+
1. Select the **Free** _SKU_
219+
1. Click the **Sign-in with GitHub** button and authenticate with GitHub
220+
1. Select your preferred _Organization_
221+
1. Select **my-vanilla-api** from the _Repository_ drop-down
222+
1. Select **master** from the _Branch_ drop-down
223+
1. Click the **Next: Build >** button to edit the build configuration
224+
225+
:::image type="content" source="media/add-api/create-static-app-on-azure-portal-2.png" alt-text="Create static app on the Azure portal - screen 2":::
226+
227+
Next, add the following the build details.
228+
229+
1. Enter **./** for the _App location_
230+
1. Enter **api** in the _Api location_ box
231+
- This is the name of the API folder created in the previous step.
232+
1. Clear the default value out of the _App artifact location_, leaving the box empty
233+
1. Click **Review + create**
234+
235+
| Setting | Description | Required |
236+
| -------- | ----------------------- |
237+
| App location | The location of the static application source code | Yes |
238+
| Api location | The location of the API backend. This points to the root folder of the Azure Functions App project | No |
239+
| App artifact location | The location of of the build output folder. Some front-end JavaScript frameworks have a build step that places production files in a folder. This setting points to the build output folder. | No |
240+
241+
:::image type="content" source="media/add-api/create-static-app-on-azure-portal-3.png" alt-text="Create static app on the Azure portal - screen 3":::
242+
243+
1. Click **Create**
244+
1. Wait for deployment to finish (this may take a minute)
245+
1. Navigate to `https://github.com/<YOUR_GITHUB_ACCOUNT>/my-vanilla-api/actions?query=workflow%3A"Azure+Pages+CI%2FCD"`
246+
1. Make sure the build is successful
247+
248+
:::image type="content" source="media/add-api/github-workflow-0.png" alt-text="GitHub Workflow":::
249+
250+
The deployed API will be available at `https://<STATIC_APP_NAME>.azurestaticapps.net/api/<FUNCTION_OR_ROUTE_NAME>`.
251+
252+
:::image type="content" source="media/add-api/github-workflow-1.png" alt-text="GitHub Workflow":::
253+
254+
You can also find the application URL from the Azure portal:
255+
256+
:::image type="content" source="media/add-api/static-app-url-from-portal.png" alt-text="Access static app URL from the Azure portal":::
257+
258+
Alternatively you can directly access your Azure Static Web App at `https://<STATIC_APP_NAME>.azurestaticapps.net` and check the result in the browser.
259+
260+
## Clean up resources
261+
262+
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.
263+
264+
1. Navigate to the [Azure portal](https://portal.azure.com)
265+
1. In the top search bar, type **Resource groups**
266+
1. Click **Resource groups**
267+
1. Select **myResourceGroup**
268+
1. On the _myResourceGroup_ page, make sure that the listed resources are the ones you want to delete.
269+
1. Select **Delete**
270+
1. Type **myResourceGroup** in the text box
271+
1. Select **Delete**.
272+
273+
274+
## Next steps
275+
276+
> [!div class="nextstepaction"]
277+
> [Configure environment variables](./environment-variables.md)
31.7 KB
Loading
45.9 KB
Loading
39.7 KB
Loading
64.2 KB
Loading
106 KB
Loading
81.2 KB
Loading
139 KB
Loading
164 KB
Loading
61.7 KB
Loading

0 commit comments

Comments
 (0)