lazyplatypus / week1changes

0 stars 0 forks source link

Week1 #3

Open lazyplatypus opened 3 years ago

ghost commented 3 years ago

Week 1 Step 3

Postman, APIs, and requests

:question: What is Postman and why do we need it?
Later, when we begin to code our Azure Function, we are going to need to test it. **How?** Just like our final web app and the first function we will code, we'll be sending requests to the Function's endpoint.

You can install Postman from the Chrome Store as a Chrome extension, or sign up here

:question: What is Postman going to do?
1. After this step, we will code an Azure Function that needs testing. 2. We will also later use Postman to **send a POST request** to our Azure Function to test if it works, mimicking what our static website will do. Our HTTP trigger Azure Functions will be an [API](https://www.youtube.com/watch?v=s7wmiS2mSXY) that receives requests and sends back information. To introduce you to sending requests to an API and how Postman works, we'll be **sending a GET request to an API this time.**

:exclamation: Getting Started with Postman
1. You can choose to sign up or skip and go directly to the app. 2. Close out all the tabs that pop up until you reach **this screen** ![image](https://user-images.githubusercontent.com/69332964/98034295-c46a9380-1de4-11eb-8f8d-ca508f4e04ef.png)

:pencil: Task 4: Send a GET request to the Cat Picture API and receive a cat picture with "Bitcamp" written on it in a specified color and text size.

Try it out yourself:

Stuck? Check here:
1. **Specifying the API Endpoint:** Enter https://cataas.com/cat/cute/says/Bitcamp, which is the API endpoint, into the text box next to GET ![image](https://user-images.githubusercontent.com/69332964/98034882-ad787100-1de5-11eb-83fd-9cb73f78beae.png) 2. **Setting Parameters:** Click on "Params" and enter `color` into Key and the color you want (eg. blue) into Value. Enter `size` into the next Key row and a number (eg. 50) into Value. > **Note on parameters:** > * the `size` parameter refers to the font size of your caption. It has a limit at around 1,200. > * Colors are pretty hit or miss; since the Cat API is on the web, but it generally adheres to HTML color names. Expect values such as "blue, green, yellow" to work. > * The API can take very large words as input for the caption, however only **34** characters can be seen on the picture at one time . 3. **Click `Send` to get your cat picture**

Interested in playing around with the API? Documentation is here.

:camping: To move on, comment your cat picture đŸ±

lazyplatypus commented 3 years ago

![Uploading Mi_Amor 112x112.png
]()

ghost commented 3 years ago

Week 1 Step 4

Writing Your First Function

Configuring Azure

This week, you will be going through steps to set up tools needed to be successful in this camp. If you are already familiar with some, feel free to skip to the end and complete the task to move on.

The Cloud

:question: So what is "The Cloud"?
![http://infomotions.com/musings/waves/media/client-server-illustration.gif](http://infomotions.com/musings/waves/media/client-server-illustration.gif) > A [server](https://www.infotech.co.uk/blog/it-infrastructure-what-does-a-server-actually-do) is a computer that provides (serves) data to other computers, called clients. Client connect to servers through the internet. Clients communicate with servers with through HTTP requests. For example, when you are on your favorite browser and look up YouTube.com, you are making an HTTP get request to the server to load the contents from YouTube.com. > ["The cloud"](https://www.cloudflare.com/learning/cloud/what-is-the-cloud/) refers to servers that are accessed over the Internet, and the software and databases that run on those servers. Cloud servers are located in data centers all over the world. By using cloud computing, users and companies don't have to manage physical servers themselves or run software applications on their own machines. Watch the 5 min video below before continuing to understand what the cloud is: [![ "What is The Cloud as Fast As Possible"](http://img.youtube.com/vi/dsKIpLKo8AE/0.jpg)](http://www.youtube.com/watch?v=dsKIpLKo8AE "What is The Cloud as Fast As Possible") If you want to learn more about Azure and all its cloud applications, feel free to check out this [link](https://azure.microsoft.com/en-us/overview/what-is-azure/), an overview of its capabilities.

:question: What are serverless functions?
Similarly, serverless functions are cool since they engage the use of serverless computing without the customer (you) having to worry about server space. This allows you to deploy code quickly and easily. Here's a great explanation of [Serverless Demystified](https://dev.to/kbariotis/serverless-demystified-333k) [âšĄïž 10 Ways to Use Serverless Functions](https://dev.to/aws/10-ways-to-use-serverless-functions-bme)

:question: What is Azure?
**According to Microsoft:** > Azure is an ever-expanding set of cloud services to help your organization meet your business challenges. It’s the freedom to build, manage, and deploy applications on a massive, global network using your favorite tools and frameworks.

:exclamation: How do I create an account?
1. To create an Azure account, go to: https://azure.microsoft.com/en-us/free/ and press **Start free** to be relocated to a signup page. ![register](https://user-images.githubusercontent.com/69332964/113362023-5dadbf80-931b-11eb-814c-5ec22c2f818d.png) 2. 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](https://azure.microsoft.com/en-us/get-started/) provided by Microsoft.

HTTP Trigger Functions

:question: What is an HTTP Trigger Serverless Function?
When you create an serverless function, you needs to be able to "trigger" the function when you need to use/access it. What does it mean to trigger something? Triggering is the same as "invoking" or calling upon the function. Let's say we have created simple a function that provides us with the current time. We can create a timer trigger that will invoke/call upon that function at some scheduled times in day, for example, every night at 10pm when it's time for bed. What is an HTTP trigger? An HTTP trigger is one that can be used to invoke a serverless function with an HTTP request.

:exclamation: How can I create a resource and deploy a simple HTTP trigger function with it?
1. Click “Create a resource” in your [portal](https://portal.azure.com/) (near the top left of the screen) resourceCreate 2. Choose “Function App” (it should be in the list of popular resources, with the lightning logo, but you should also be able to search it in the marketplace) FunctionApp 3. Create a new resource group, with a unique resource name (related to what your app does e.g. "TimeFunction"). Add a unique Function App name as well (e.g. "ShreyasTimeApp"). 4. Make sure the "Code" button is selected next to Publish, the Runtime stack is Node.js, and the Version selected is 12 LTS codeDocker 5. Select your region 6. All of the other tabs in this step should be correctly filled (you can double-check them if you want), so you should be ready to click "Review+Create" and then “Create” 7. Deploying may take a few minutes – be patient! Once the function is deployed, open it. ![go to resource](https://user-images.githubusercontent.com/28051494/114977384-6da9c100-9e3c-11eb-9651-9ad8fac6bc04.png) 9. Go to the “Functions” tap on the left (with symbol {fx}). ![resource](https://user-images.githubusercontent.com/28051494/114977495-96ca5180-9e3c-11eb-9114-30f74a255dbb.png) 10. Click “Add” on this page, and then search “HTTP trigger” (in the side window that opens) ![add function](https://user-images.githubusercontent.com/28051494/114977534-a9448b00-9e3c-11eb-9510-3707e84ca1ac.png) 12. Click “Add” (at the bottom of the side window) – creating this HTTP trigger may take a few seconds, so remember: patience! httpTrigger 11. Once this trigger is created, it should automatically open. Click the “Code + Test” tab on the left side, and you should be able to see and edit the code. code+Test 12. Click “Save” and “Refresh” (in that order, and refresh only once the trigger has completely saved) when you have finished writing your code (or in between – it never hurts). 13. Click “Test/Run” once you are ready to try out your new trigger function. If it all works smoothly, and the code has no errors, you should receive an output that says "Hello, Azure. This HTTP triggered function executed successfully." ![output](https://user-images.githubusercontent.com/28051494/114978046-8666a680-9e3d-11eb-800a-9298a74deeb8.png)

:exclamation: How can I use my function?
Let's try triggering this function! Click on the "Get function URL" button and copy 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. ![trigger the function](https://media.giphy.com/media/gK86LCd5HiEUpz1t0i/giphy.gif) First let's try to understand what is happening here: ```javascript 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 }; } ``` The context.log statement at the top of the function is there to indicate to the developer (you) anytime a trigger has been made. Next, we have a constant variable called name that can be passed in through the query parameters (the Input section when you click "Test & Run"). Below this, we have a "conditional ternary operator" which allows us to make a simple conditional statement (if something is true, do this, else/otherwise do that) efficiently. ```javascript //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."; ``` In this case, 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`. Once you have made sure that the function is saved, let's try running it again but now with new query parameters. In the variable definition of `name` we enable the function get the value of `name` in two ways. Let's test it out: 1. In the input, create a new Query parameter with the Name "name" and your name for the Value. query parameters 2. Run the function and check the HTTP response content - make sure that the output now contains your name. output 3. Next, let's try to use the body to change the name. In the input body, change "Azure" to another name (a different name) in double quotes and run the function. You should notice that the output still contains the first name you provided. Check out the code and see if you can figure out why this is.
:question: Why does the function output prioritize the Query parameter over the body parameter?
```javascript const name = (req.query.name || (req.body && req.body.name)); ``` In the name variable definition you will see that or || operator. This indicates that the value of name can either be `req.query.name` or `req.body && req.body.name`. Because of the order of the options, it will take the first value if the first value exists. Thus, if we want to use the body, we will need to remove the name parameter from the query.

4. In the Input, remove the name query parameter and try running the function again. output Try editing this function on your own! *(Don't forget to save when you make changes!)*

One more tip: don’t forget to save! Rewriting code can be challenging and extremely frustrating, so save yourself the trouble!

:pencil: Task 3: Create and deploy an HTTP trigger Azure Function that outputs the current time and date.

Example output:

Hello! The current time is: 17 : 41 : 34 PM

This time we'll try developing locally. Follow the directions in this link to set up and deploy your first Azure Function right in your local machine.

:question: Not sure where to start?
We need to edit the function so that it returns the current time. 1. First start by creating a variable that gets the current time (try googling "how to get current time in Javascript"). 2. Try to test your function to make sure that it is returning the time in the right format (and timezone). 3. Once you get the time printing, you can remove any extra code related to getting the parameters since we don't need that for this task. Make sure your output matches the example output with accurate current time.
:question: Still stuck? Check out the code below:
Javascript has a built in [Date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) that evaluates to the time in milliseconds since 1 January 1970 UTC (keep the timezone in mind). First you want to create an instance of the Date object: ```javascript var currentdate = new Date(); ``` Next, you can use the [Instance Methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#instance_methods) in the linked documentation to use methods that calculate the current hours, minutes, and seconds to get the current time. ```javascript var currentime = currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds(); ```



: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)

:exclamation: How should I test it?
**Option 1:** Paste the *function url* directly in your browser. Text with the current time should appear. **Option 2:** Use **Postman**! Paste the *function url* and make a GET request. In the output box, you should get something like this: ![image](https://user-images.githubusercontent.com/69332964/113361613-63ef6c00-931a-11eb-9380-7d58a3dea1b4.png)

:camping: To move on, place your function URL in a repository secret called HTTP_ENDPOINT so we can check your function. Remember to commit the function's code in a file named httptime.js to the root of the week1 branch!

Note: Every time you make a new commit to week1, 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.