Managing a server is pretty complicated. As a student, mastering serverless functions can help you to build projects that solve real-world problems by integrating APIs, constructing user interfaces, and analysing data without worrying about managing servers.
[x] Run git pull and create a new branch called hackervoice
[x] 1: Create an Azure account
[x] 2: Create an HTTP trigger Azure function that gets content from a request parameter called password and returns it in the function's body
[ ] 🚀 Place your function URL in a repository secret called HACKERVOICE_ENDPOINT and commit the function's code in a file named HackerVoice/index.js on the hackervoice branch
[ ] 🚀 Create a pull request that merges hackervoice to main, but do not merge it
🚧 Test your Work
Option 1:
Paste the function url directly in your browser and add the query parameters to the end of the url: ¶m_name=param_value. Your inputted password value should appear.
Option 2:
Use Postman! Paste the function url and make a GET request. In the output box, you should receive the value you put in for the request parameter.
1: Introducing Azure
Azure is Microsoft's cloud computing platform (similar to Google Cloud Platform and Amazon Web Services)
To create an Azure account, go to Microsoft Azure and press Start Free.
After signing in with your Microsoft account and filling in your personal details, you will be asked to add a credit card.
Rest assured, this is only for security purposes (preventing multiple free accounts per person), and you won't be charged unless you choose to buy a premium account, which we do not need for this course.
If you need some help navigating Azure, check out this super helpful resource provided by Microsoft.
2: HTTP Trigger Functions
When you create an serverless function, you need to be able to "trigger" (call) the function when you want to use/access it using an HTTP request. This allows us to save a lot of money because we only have to run the servers when we need them. An HTTP trigger is one that can be used to invoke a serverless function with an HTTP Request.
Creating and deploying a simple HTTP trigger function
:exclamation: Create a local project
1. Click on the Azure icon in the Activity bar (leftmost vertical menu on VS Code). If you hover over the FUNCTIONS dropdown, you will see a bunch of icons appear on the right. Select the Create New Project icon that looks like a folder with a lightning bolt on it.
2. Choose a directory location for your project workspace and choose Select.
3. Provide the following information at the prompts:
* Select a language for your function project: Choose JavaScript.
* Select a template for your project's first function: Choose HTTP trigger.
* Provide a function name: Type HttpExample.
* Authorization level: Choose Anonymous, which enables anyone to call your function endpoint. To learn about authorization level, see Authorization keys.
* Select how you would like to open your project: Choose Add to workspace.
4. Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger. You can view the local project files in the Explorer. To learn more about files that are created, see Generated project files.
This is what your VS Code should look like after creating the local project:
:exclamation: Publish the project to Azure
In this section, you create a function app and related resources in your Azure subscription and then deploy your code.
1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app... button.
2. Provide the following information at the prompts:
* **Select folder**: Choose a folder from your workspace or browse to one that contains your function app. You won't see this if you already have a valid function app opened.
* **Select subscription**: Choose the subscription to use. You won't see this if you only have one subscription.
* **Select Function App in Azure**: Choose + Create new Function App. (Don't choose the Advanced option, which isn't covered in this article.)
* **Enter a globally unique name for the function app:** Type a name that is valid in a URL path. The name you type is validated to make sure that it's unique in Azure Functions.
* **Select a runtime**: Choose the version of Node.js you've been running on locally. You can use the node --version command to check your version.
* **Select a location for new resources**: For better performance, choose a [region](https://azure.microsoft.com/en-us/global-infrastructure/geographies/) near you.
:exclamation: Run the function 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.
1. To call your function, press F5 to start the function app project. Output from Core Tools is displayed in the Terminal panel. Your app starts in the Terminal panel. You can see the URL endpoint of your HTTP-triggered function running locally.
If you have trouble running on Windows, make sure that the default terminal for Visual Studio Code isn't set to WSL Bash.
2. With Core Tools running, go to the Azure: Functions area. Under Functions, expand Local Project > Functions. Right-click (Windows) or Ctrl - click (macOS) the HttpExample function and choose Execute Function Now....
3. In Enter request body you see the request message body value of { "name": "Azure" }. Press Enter to send this request message to your function.
You could have instead sent an HTTP GET request to the http://localhost:7071/api/HttpExample address in a web browser.
4. When the function executes locally and returns a response, a notification is raised in Visual Studio Code. Information about the function execution is shown in Terminal panel.
5. Press Ctrl + C to stop Core Tools and disconnect the debugger.
After you've verified that the function runs correctly on your local computer, it's time to use Visual Studio Code to publish the project directly to Azure.
:exclamation: Sign into Azure
Before you can publish your app, you must sign in to Azure.
1. If you aren't already signed in, choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose Sign in to Azure.... If you don't already have one, you can [Create a free Azure account](https://azure.microsoft.com/en-us/free/). Students can [create a free Azure account for Students](https://azure.microsoft.com/en-us/free/students/).
If you're already signed in, go to the next section.
2. When prompted in the browser, choose your Azure account and sign in using your Azure account credentials.
3. After you've successfully signed in, you can close the new browser window. The subscriptions that belong to your Azure account are displayed in the Side bar.
Understand the Code
Open index.js and check out the code. It should look almost exactly like this:
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
}
Let's go line by line:
Start of function definition: module.exports = async function
Print comment in Azure Console anytime the function is triggered: context.log()
Get parameter from request body (in sample.dat file): const name
Conditional (ternary) operator to print message if parameter exists (else print error message):
//condition: if name exists
name
//? is chosen if the condition evaluates to true
? "Hello, " + name + ". This HTTP triggered function executed successfully."
//: is chosen if the condition evaluates to false
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
We have additionally assigned the results of that conditional ternary statement to another variable called responseMessage so that we can return the result of the Azure Function using context.res
Trigger the function
Let's try triggering this function! Locate this function on the Azure portal and get the function url, then go ahead and paste it into a new tab. You will be able to see this in the log in your Azure portal, every time your trigger the function.
One more tip: don’t forget to save! Rewriting code can be challenging and extremely frustrating, so save yourself the trouble!
Creating a Request Parameters
Request parameters are a way for an HTTP request to take in information! They are pretty much identical in purpose to why you would want a parameter for a function in a coding language. In this instance, we will need a parameter for the password.
Look at the code for a basic HTTP Function:
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
}
Request parameters are a property of the req or request parameter of the module. The request has a query object that stores all of the parameters passed in. You don't need to specify what parameters the user needs to input into the HTTP request, but can acess any parameters that are sent in. You would access a parameter by calling on the query like this:
<property name> = req.query.<your property here>;
for instance, if you were looking for a color parameter, you can access it with the following code
color = req.query.color;
Note: your parameter must be named password
:question: Where's the function URL?
Go to the function trigger you are working on, and find this button above the code.
![code](https://user-images.githubusercontent.com/69332964/99188529-73369a00-272a-11eb-93df-04fdce5381df.png)
Note: Every time you make a new commit to hackervoice, we will check your function by making a request.
:exclamation: How do I add a respository secret?
[Here are some steps:](https://docs.github.com/en/actions/reference/encrypted-secrets#creating-encrypted-secrets-for-a-repository)
1. On GitHub, navigate to the main page of the repository.
2. Under your repository name, click `Settings`.
![settings](https://docs.github.com/assets/images/help/repository/repo-actions-settings.png)
3. In the left sidebar, click Secrets.
4. Click New repository secret.
5. Type a name for your secret in the Name input box.
6. Enter the value for your secret.
7. Click Add secret.
Week 1 Step 4 ⬤⬤⬤⬤◯◯◯◯◯ | 🕐 Estimated completion: 35-45 minutes
Building our first function ⚡[HackerVoice]
✅ Tasks:
git pull
and create a new branch calledhackervoice
password
and returns it in the function's bodyHACKERVOICE_ENDPOINT
and commit the function's code in a file namedHackerVoice/index.js
on thehackervoice
branchhackervoice
tomain
, but do not merge it🚧 Test your Work
Option 1: Paste the function url directly in your browser and add the query parameters to the end of the url:
¶m_name=param_value
. Your inputted password value should appear.Option 2: Use Postman! Paste the function url and make a GET request. In the output box, you should receive the value you put in for the request parameter.
1: Introducing Azure
Azure is Microsoft's cloud computing platform (similar to Google Cloud Platform and Amazon Web Services)
To create an Azure account, go to Microsoft Azure and press Start Free.
After signing in with your Microsoft account and filling in your personal details, you will be asked to add a credit card.
If you need some help navigating Azure, check out this super helpful resource provided by Microsoft.
2: HTTP Trigger Functions
When you create an serverless function, you need to be able to "trigger" (call) the function when you want to use/access it using an HTTP request. This allows us to save a lot of money because we only have to run the servers when we need them. An HTTP trigger is one that can be used to invoke a serverless function with an HTTP Request.
Creating and deploying a simple HTTP trigger function
:exclamation: Create a local project
1. Click on the Azure icon in the Activity bar (leftmost vertical menu on VS Code). If you hover over the FUNCTIONS dropdown, you will see a bunch of icons appear on the right. Select the Create New Project icon that looks like a folder with a lightning bolt on it.2. Choose a directory location for your project workspace and choose Select. 3. Provide the following information at the prompts: * Select a language for your function project: Choose JavaScript. * Select a template for your project's first function: Choose HTTP trigger. * Provide a function name: Type HttpExample. * Authorization level: Choose Anonymous, which enables anyone to call your function endpoint. To learn about authorization level, see Authorization keys. * Select how you would like to open your project: Choose Add to workspace. 4. Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger. You can view the local project files in the Explorer. To learn more about files that are created, see Generated project files.
This is what your VS Code should look like after creating the local project:
:exclamation: Publish the project to Azure
In this section, you create a function app and related resources in your Azure subscription and then deploy your code. 1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app... button.2. Provide the following information at the prompts: * **Select folder**: Choose a folder from your workspace or browse to one that contains your function app. You won't see this if you already have a valid function app opened. * **Select subscription**: Choose the subscription to use. You won't see this if you only have one subscription. * **Select Function App in Azure**: Choose + Create new Function App. (Don't choose the Advanced option, which isn't covered in this article.) * **Enter a globally unique name for the function app:** Type a name that is valid in a URL path. The name you type is validated to make sure that it's unique in Azure Functions. * **Select a runtime**: Choose the version of Node.js you've been running on locally. You can use the node --version command to check your version. * **Select a location for new resources**: For better performance, choose a [region](https://azure.microsoft.com/en-us/global-infrastructure/geographies/) near you.
:exclamation: Run the function 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. 1. To call your function, press F5 to start the function app project. Output from Core Tools is displayed in the Terminal panel. Your app starts in the Terminal panel. You can see the URL endpoint of your HTTP-triggered function running locally. If you have trouble running on Windows, make sure that the default terminal for Visual Studio Code isn't set to WSL Bash.2. With Core Tools running, go to the Azure: Functions area. Under Functions, expand Local Project > Functions. Right-click (Windows) or Ctrl - click (macOS) the HttpExample function and choose Execute Function Now....
3. In Enter request body you see the request message body value of { "name": "Azure" }. Press Enter to send this request message to your function. You could have instead sent an HTTP GET request to the http://localhost:7071/api/HttpExample address in a web browser. 4. When the function executes locally and returns a response, a notification is raised in Visual Studio Code. Information about the function execution is shown in Terminal panel. 5. Press Ctrl + C to stop Core Tools and disconnect the debugger. After you've verified that the function runs correctly on your local computer, it's time to use Visual Studio Code to publish the project directly to Azure.
:exclamation: Sign into Azure
Before you can publish your app, you must sign in to Azure. 1. If you aren't already signed in, choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose Sign in to Azure.... If you don't already have one, you can [Create a free Azure account](https://azure.microsoft.com/en-us/free/). Students can [create a free Azure account for Students](https://azure.microsoft.com/en-us/free/students/).If you're already signed in, go to the next section. 2. When prompted in the browser, choose your Azure account and sign in using your Azure account credentials. 3. After you've successfully signed in, you can close the new browser window. The subscriptions that belong to your Azure account are displayed in the Side bar.
Understand the Code
Open index.js and check out the code. It should look almost exactly like this:
Let's go line by line:
Start of function definition:
module.exports = async function
Print comment in Azure Console anytime the function is triggered:
context.log()
Get parameter from request body (in sample.dat file):
const name
Conditional (ternary) operator to print message if parameter exists (else print error message):
We have additionally assigned the results of that conditional ternary statement to another variable called
responseMessage
so that we can return the result of the Azure Function usingcontext.res
Trigger the function
Let's try triggering this function! Locate this function on the Azure portal and get the function url, then go ahead and paste it into a new tab. You will be able to see this in the log in your Azure portal, every time your trigger the function.
One more tip: don’t forget to save! Rewriting code can be challenging and extremely frustrating, so save yourself the trouble!
Creating a Request Parameters
Request parameters are a way for an HTTP request to take in information! They are pretty much identical in purpose to why you would want a parameter for a function in a coding language. In this instance, we will need a parameter for the password.
Look at the code for a basic HTTP Function:
Request parameters are a property of the
req
or request parameter of the module. The request has aquery
object that stores all of the parameters passed in. You don't need to specify what parameters the user needs to input into the HTTP request, but can acess any parameters that are sent in. You would access a parameter by calling on the query like this:for instance, if you were looking for a color parameter, you can access it with the following code
:question: Where's the function URL?
Go to the function trigger you are working on, and find this button above the code. ![code](https://user-images.githubusercontent.com/69332964/99188529-73369a00-272a-11eb-93df-04fdce5381df.png)Note: Every time you make a new commit to
hackervoice
, we will check your function by making a request.:exclamation: How do I add a respository secret?
[Here are some steps:](https://docs.github.com/en/actions/reference/encrypted-secrets#creating-encrypted-secrets-for-a-repository) 1. On GitHub, navigate to the main page of the repository. 2. Under your repository name, click `Settings`. ![settings](https://docs.github.com/assets/images/help/repository/repo-actions-settings.png) 3. In the left sidebar, click Secrets. 4. Click New repository secret. 5. Type a name for your secret in the Name input box. 6. Enter the value for your secret. 7. Click Add secret.