shreythecray / streamtest

0 stars 0 forks source link

Getting Started with Serverless #1

Open ghost opened 3 years ago

ghost commented 3 years ago

Week 1 Step 1 ⬤◯◯◯◯◯◯◯◯ | 🕐 Estimated completion: 5-20 minutes

GitHub

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.

✅ Task:

What is GitHub?

GitHub is a industry-standard platform allows developers to save and collaborate on code. You can use GitHub to manage your files, changes in your project, version control (the ability to revert back to previous versions of your code as well as versions developed by other programmers), and more.

Check out "The Github Flow" for more information on issues, pull requests, committing, and branches!

If you want to learn more about what it is and how to use it, try taking this GitHub Learning Lab Course. After finishing it, you will have a strong understanding of all the features GitHub has to offer.

✍️Vocabulary #### Repositories Repositories (or repos) are essentially **folders where you can store files of code.** The repo of our camp was duplicated into your account when you clicked "Create Template" so that you can commit changes and complete each lesson. #### Issues For our camp, each week is placed inside an issue. Only when you complete the week (committing the necessary code and commenting), will the issue close and you can move on to the next issue. Don’t worry – committing changes is easier than it sounds. *On usual repositories in the contributing world issues are tasks or bugs that need to be completed or fixed.* #### Fork If you want to contribute to someone else's code, you would "fork" it. This creates a copy of the code under your account that you can make changes to. Create a fork when you **want to make changes to someone else's code and contribute to it.** #### Branch Creating a **branch** on a repository is like forking a repository. You would do this when you **want to make changes to your code without harming a working version.** #### Pull Request Once you make changes on **a forked repository or another branch,** you might need to bring the changes into the "main" repository. This allows YOUR changes to be visible in the main project! *You are basically asking for permission to "merge" your changes." **This allows you to:** * Collaborate on code * Make comments * Review the contributions made #### Command Line Interface A Command Line Interface (CLI) is your computer's visual application for accessing its operating system. There are different types of CLIs for different operating systems, such as Terminal for MacOs and PowerShell for Windows. If you have Windows, make sure to also install [Git Bash](https://git-scm.com/downloads) for a better tool. In upcoming issues, we will refer to your CLI as your Terminal or Command Line, but remember that they mean the same thing!

:bulb: Try to not use the web editor! Commit from your command line.

Commiting to a repository using a command line?

Setting up

Start out by downloading Git. Then, open your command line.

The commands

Navigate to the directory in your command line where you want to keep your repository.

Tip: Use cd ./your-directory to change directories, pwd to find out where you are, and ls to list files & directories. More information is here.

Cloning your repository Click on "Code" on your repo's page and find your repo's HTTP link: ![image](https://user-images.githubusercontent.com/69332964/116948751-53e6e700-ac4e-11eb-821a-23ccca60f046.png) Enter this command **and replace the url** to get your repository's files onto your local computer. ``` git clone https://github.com/example/example.git ``` Now is the time to make your changes to your code!
Committing and pushing code First, "stage" your changes. You will be specifying what files you want to commit the changes of. Stage `helloworld.js` changes only: ``` git add helloworld.js ``` Stage ALL your changes to the repository: ``` git add -A ``` Next, let's commit the code. Usually, your commits will be a group of changes that make sense together. *Add a description!* ``` git commit -m "insert your description" ``` Save your commits to the repository on Github! ``` git push ``` **For more information, refer to [this link](https://docs.github.com/en/github/managing-files-in-a-repository/adding-a-file-to-a-repository-using-the-command-line)**


Congrats! Your changes should now be visible on Github

:exclamation: Don't forget to git pull before making any changes to your local repo!! This gets any changes that were made by the bot.

Key functions you should be familiar with after this task include:

ghost commented 3 years ago

Week 1 Step 2 ⬤⬤◯◯◯◯◯◯◯ | 🕐 Estimated completion: 5-20 minutes

Say "Hello" to VSCode

✅ Task:

🚧 Test your Work

If you run node helloworld.js in the terminal, the output should be Hello World

Note: From now on, you will never need to close an issue. The Counselor will do that for you, create new issues, and new comments for further instructions!

The IDE - Visual Studio Code

Before we start coding, we need to install an IDE. An IDE is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools, and a debugger. Although there are hundreds of IDEs to choose from, we are going to use Visual Studio Code due to its popularity and integration with Azure (via extensions and libraries).

:computer: How to set up your VSCode Environment
To install VSC, go to: https://code.visualstudio.com/download and choose your operating system (ie. Windows, Mac, Linux, etc). Then click **Download** and run the installer (usually a `.exe` or `.zip` file). After it's installed, open it up and try it out. If you need some help navigating VSC, check out this super helpful YouTube video. Inside VSCode, you downloaded four extensions: **Azure Account, Azure App Service, Azure Functions, and Live Server.** All of the Azure extensions allow you to work on your Azure Function App in VS code instead of working directly through the Microsoft portal. Live Server is a quick and temporary testing server, and you can use it to test HTML pages. To launch, right click on your html file and press "Open with Live Server" or click "Go Live" in the bottom right corner: Screen Shot 2021-01-10 at 1 53 20 PM Screen Shot 2021-01-10 at 1 53 40 PM

:exclamation: How do I use GitHub on VS Code? 1. Check out this awesome documentation about [how to set up Git on your local computer](https://docs.github.com/en/github/getting-started-with-github/set-up-git) 2. Once you have complete the steps in the documentation, clone this repo on your computer 3. Use the following commands to work with branches in the terminal: - Check which branch you're in: `git branch` - Create a new branch and change into it: `git checkout --b name-of-branch` - Change branch: `git checkout name-of-branch` 4. Afterwards, follow [this tutorial](https://code.visualstudio.com/docs/editor/github) by VS Code on connecting to GitHub straight from the app!

Note: Dark Theme is our personal favorite, but feel free to choose whichever theme you like best. Go to this site to view your options!

:exclamation: Don't forget to git pull before making any changes to your local repo!!

Writing and Exporting a Javascript function

JavaScript enables the ability to export functions in a program so that you can access them in other parts of the program via the import statement. In this case, we want to export your programs in order for CounselorBot to check your code.

:exclamation: What are JavaScript and Node?
Javascript is the language of the internet! It is a powerful tool for creating complex web apps. However, JavaScript can be used for building the client for applications, and sometimes requires a way to access this client, which is also known as the server-side. Node.js is the solution to this problem, and allows you to write and run code not linked to a website locally. If you would like to read more, refer to [this article](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript) on JavaScript and [this article](https://www.tutorialspoint.com/nodejs/nodejs_introduction.htm) on Node.

:exclamation: How do I export a function?
Let's say your function name is `hello`. To export it, add this line of code at the very bottom of your file outside of your function: `module.exports = hello`. Example: ```js function hello() { // your code } module.exports = hello ``` When you commit the file, we will try to run the function by importing it and compare it's output to the expected output like so: ```js let hello = require('../../week1/helloworld.js') let output = hello() ``` #### How does this apply to code in the real world? Just like you can import code from modules other people have written, you can also **import functions you wrote from *other files* to reuse them.** In function oriented programming, you use functions over and over again to save code. If you want to use the function `hello()` in another file, you would need to import it.

:exclamation: Can I have more detailed steps?
1. Create a new file 2. Name the file helloworld.js 3. Write your code 4. If you have node installed on your computer, open terminal on VS Code and type 'node helloworld.js' 5. If you have not installed node on your computer, you will need to do that first: https://nodejs.org/en/download/ 6. Tip: to test your function, call it in your code. 7. Create a new branch named `week1` and commit your `helloworld.js` file in the root directory.

ghost commented 3 years ago

Week 1 Step 3 ⬤⬤⬤◯◯◯◯◯◯ | 🕐 Estimated completion: 10-15 minutes

Getting Cat Pics with Postman 🐱

✅ Task:

Postman

In this step, we'll be using a software called Postman to test a premade API. Postman is a debugging tool for RESTful APIs, which allows you to test both pre-existing, community made APIs, or your own self-made APIs, without having to write any HTML test code!

You can sign up for Postman here.

:exclamation: Why Postman?
While VS Code has its own [REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) extension, Postman is an industry-standard tool that would be advantageous to learn in the case that you don't have access to a built-in debugging tool for REST APIs. We are using the online version to save space, but there is also a desktop version that you can download using [this link](https://www.postman.com/downloads/). If you would like, feel free to use VS Code's extension instead of Postman.

In this step, you will be using Postman to test the Cataas API by sending a GET request.

Don't worry, we'll tell you what all that means in a moment!

What is the Cloud?

"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.

What are APIs, and what makes one "RESTful?"

An API is a piece of software that lets two other pieces of software talk to each other! Imagine you're driving a car - the wheel and pedals would be like APIs between you and the car, since they allow you to controll the car easily.

Most of the time, an API will be used to connect an app to an external service. For example, the Twitter API could allow a user to automatically receive updates on tweets concerning a particular topic or event.

What does it mean to be "RESTful," though? Any API that follows these 5 rules is, by definition, RESTful. **You don't need to worry about the 5 rules**, but if you're curious... 1. Internally, the API should keep the things the user does and the things the server does separate. 2. The server shouldn't ever need to store the user's data to function. 3. All output data from the API should mark itself as either "cacheable" or "non-cacheable" (cacheable data can be stored and reused later by the user, while non-cacheable data should be discarded and recomputed by the API every time). 4. The user shouldn't be able to tell whether or not they're communicating with the API's server, or an intermediary server. 5. The interface of the API should conform to a few agreed-upon conventions (that we won't be going over here).

What are HTTP Requests?

A server is a computer that provides (serves) data to other computers, called clients. Clients 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.

:exclamation:What are some examples of request types??
Below are some of the most common HTTP requests. Read through each one, and try to get familiar with their functions! **Get Request**: gets data from a server (hence the name). The data we want is specified using a URL we call a Request URL. In this case, you will use a Get Request URL from the Catass API to receive a cat picture. **Post Request**: used to send data to a server, to create or update a resource. The information submitted to the server is archived in the request body of the HTTP request. This is often used to send user-generated data to a server. An example could be uploading a picture to a Post URL. **Put Request**: similar to a Post Request, but a put request will always have the same result every time you use one, whereas a post request might not. We call this property "idempotency." **Delete Request**: used to delete resources indicated by the URL and will remove the targeted resources.

The Cataas (Cats as a Service) API

CATAAS is a RESTful API that exclusively delivers images of cats. The main feature is that we can change the properties of images, add text, truncate the image, add a filter and more. It's not an API with many real-world applications, but it's perfect for learning.

Open up Postman and try it out yourself:

Stuck? Check here:
1. **Specifying the API Endpoint:** Enter https://cataas.com/cat/cute/says/Serverless, 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.

How to Navigate Postman's UI

https://media.giphy.com/media/Kxs6TTeI4siCJKKRMC/giphy.gif

:question: How do we build requests? The [Postman documentation](https://learning.postman.com/docs/sending-requests/requests/) covers: * Creating requests * Adding request detail * Setting request URLs * Selecting request methods * Sending parameters * Sending body data * Authenticating requests * Configuring request headers
lazyplatypus commented 3 years ago

my cat was supposed to be here

Frame 10

ghost commented 3 years ago

Week 1 Step 4 ⬤⬤⬤⬤◯◯◯◯◯ | 🕐 Estimated completion: 35-45 minutes

Building our first function ⚡[HackerVoice]

✅ Tasks:

🚧 Test your Work

Option 1: Paste the function url directly in your browser and add the query parameters to the end of the url: &param_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 get whatever value you put in for the request parameter.

What are serverless functions?

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.

⚡️ 10 Ways to Use Serverless Functions

Azure

Azure is Microsoft's cloud computing platform! We will be using it for all of our projects, but other alternatives such as Google Cloud Platform and Amazon Web Services also exist.

: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

When you create an serverless function, you need to be able to "trigger" the function when you want to use/access it. 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.

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.

Creating and deploying a simple HTTP trigger function

:exclamation: How do I create a local project?
1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, select the Create new project... icon. ![create new project](https://docs.microsoft.com/en-us/azure/azure-functions/media/functions-create-first-function-vs-code/create-new-project.png) 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.
: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: How do I run my 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. ![running in command line](https://docs.microsoft.com/en-us/azure/includes/media/functions-run-function-test-local-vs-code/functions-vscode-f5.png) 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.... ![executing function](https://docs.microsoft.com/en-us/azure/includes/media/functions-run-function-test-local-vs-code/execute-function-now.png) 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 in 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/). ![signing into azure](https://docs.microsoft.com/en-us/azure/includes/media/functions-sign-in-vs-code/functions-sign-into-azure.png) 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.
: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!

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.

Creating a request parameter

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 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.

ghost commented 3 years ago

Week 1 Step 5 ⬤⬤⬤⬤⬤◯◯◯◯ | 🕐 Estimated completion: 25-35 minutes

Let me in!

✅ Tasks:

🚧 Test your Work

When you paste your Function URL in your browser or make a GET request with Postman with a password parameter of letmein, you should get “Access granted.“. Otherwise, your function should return “Access denied.“.

Returning from a function?

Now that we've got the user's result, either Access denied. or Access granted., we have to get it to them somehow. We can do this by returning it in the body of the request!

:bulb: Recall the context.res object we saw in the HTTP Trigger template.

context.res = {
    // status: 200, /* Defaults to 200 */
    body: your_response
};

Place your message to the user in your_response!

Guidelines

The function should output the following responses according to whichever case is true:

ghost commented 3 years ago

Week 1 Step 6 ⬤⬤⬤⬤⬤⬤◯◯◯ | 🕐 Estimated completion: 25-35 minutes

Trying to make node-fetch happen

✅ Task:

Note: Every time you make a new commit to week1, we will check your function by making a request.

🚧 Test your Work

When you paste your Function URL in your browser or make a GET request with Postman, you might get something like:

{
    "/9j/4AAQSk..."
}
:exclamation: How can I make a request to the cat API?
**Hint:** You should try using the `node-fetch` module, but there are many other ways to do it as you can see [here](https://www.twilio.com/blog/5-ways-to-make-http-requests-in-node-js-using-async-await).
🔵 I'm still a little lost, some more help would be great!
1. Let's use the `node-fetch` module for this task. Install it on your Azure Portal console: **Step 1: Install the module** In the left tab, scroll down to **Console**. ![console](https://user-images.githubusercontent.com/52464195/93178238-cf5c4e00-f6e8-11ea-90ab-c42f746cf04e.png) Enter these commands in order: ```sh npm init -y npm install node-fetch ``` *If you're confused about what this "package" thing is, we'll explain more in depth in the next step.* **Step 2: Add it to your code** Add this line of code to reference the module at the top of your code: `const fetch = require('node-fetch)` 2. Time to make the request! ```js let resp = await fetch(THE_ENDPOINT, { method: 'GET' }); let data = await resp.arrayBuffer() // we need to receive it as a buffer since this is an image we are receiving from the API // Buffer?? https://developer.mozilla.org/en-US/docs/Web/API/Blob ``` **Your turn!** What should you place in place of `THE_ENDPOINT`? Change the code.

Return your images encoded in base64!

Base64 is just another way to represent data. We can also represent the number 11 or 0 in base64. Remember that the images you see on your screen are actually just numbers!

base64data = Buffer.from(originaldata).toString('base64')
//put what you want to turn into base64 inside "original data"
//"originaldata" will be encoded in base64.

When we're coding websites, we can use base64 to display images on websites. The base64 outputted from your API can be used to create this:

image

Base64 encoding allows programs to encode binary data into text (ASCII characters) in order to prevent data loss. We do this since there are certain transfer channels that only reliably transfer text data, and this encoding method allows us to safely transfer images in the form of text.

For fun: Once your API successfully returns the images in base64, you can see what they look like using this website.

:exclamation: Now that I've got the picture in base64, how do I return it?
`context.res` is the key to answering this question! ```js context.res = { body: { your_picture_in_base64 } } ```

ghost commented 3 years ago

Week 1 Step 7 ⬤⬤⬤⬤⬤⬤⬤◯◯ | 🕐 Estimated completion: 5-15 minutes

Name your Cat

✅ Task:

🚧 Test your Work

When you paste your Function URL in your browser or make a GET request with Postman, you might get something like:

{
  "cat1": "/9j/4AAQSk...",
  "cat2": "R0lGODlhCwHI...",
   "names": [
    "Daniel",
    "Shreya"
  ]

:bulb: The Base64 is shortened for clarity! Input the base64 into this converter to see whether your images are correct.

Hint: Remember what we did in step 6? You're going to have to make two of those requests for a two cat pictures, so create two different variables for each request to get two unique pictures.

:exclamation: How can I select random items out of a list?
**Hint 1:** You'll need to create an array with the names first. **Hint 2:** You'll need to generate a random number within the range of the array length.
🔵 I'm still a little lost, some more help would be great!
1. Create an array with the names: ```js var names = ["name1", "name2"...] ``` 2. Generate a random value in the correct range: ```js var random_value = Math.floor(names.length * Math.random()) ``` 3. Get the name! ```js var resultname = names[random_value] ``` Wrap the code for generating a random combination into a function called `nameFinder()` and return resultname. *Call nameFinder() twice to get two names!*

:exclamation: Now that I've got everything, how do I return it?
`context.res` is the key to answering this question! To return your two images and two names in the output: ```js context.res = { body: { cat1: your-first-catpicture-in-base64, cat2: your-second-catpicture-in-base64, names: [name1, name2] } } ```

ghost commented 3 years ago

Week 1 Step 8 ⬤⬤⬤⬤⬤⬤⬤⬤◯ | 🕐 Estimated completion: 5-15 minutes

[TOP SECRET] Morse Code Converter

Dwight being a spy

Welcome agent! You have made it this far so we know we can trust you. BitProject is working in an undercover operation, and we need a new way to communicate.

✅ Tasks:

Installing Packages

Create a new HTTP trigger function in your Azure portal along with the Function App. Navigate to your Function App. This is not the function code, but the actual app service resource.

We will be using the morse-code-converter npm package.

:question: Why do we need these "packages" and what are they?
Packages are awesome! They're chunks of publicly available code that someone else has written to help make coding easier for everyone else. These packages reusable code that increases functionality in your code. Before the Azure Function can run the code we will write, we have to install all the necessary package dependencies. These packages contain **code that we will "depend on" in the application**; we have to install them in the console using `npm install`. [What is a package?](https://www.w3schools.com/nodejs/nodejs_npm.asp) [What is the morse-code-converter package?](https://www.npmjs.com/package/morse-code-converter)

:question: How do I install the package?
In the left tab, scroll down to Console: ![console](https://user-images.githubusercontent.com/52464195/93178238-cf5c4e00-f6e8-11ea-90ab-c42f746cf04e.png) Enter these commands in order: ```sh npm init -y npm install morse-code-converter ```

:exclamation: Woah! What just happened when the package was installed?
The first command created a **package.json** file to store your dependencies and essentially keeps track of what packages your application needs. You can find this file by going into the left menu and clicking on "App Files". Screen Shot 2021-04-26 at 3 15 21 AM The next one actually installs the necessary packages with code, `morse-code-converter`. *Note: If you get red text like `WARN`, you can ignore it.* Screen Shot 2021-04-26 at 3 12 43 AM

:books: Reminder: don't forget to import your package! const morse = require("morse-code-converter");

:bulb: Make sure your parameter is named plaintext

Using morse-code-converter

:question: How do I receive the English as a parameter?
[Query parameters](https://rapidapi.com/blog/api-glossary/parameters/query/) can be accessed from the `req` object in the input of the `module.exports` function. > :bulb: Since ours is named `plaintext`, we can access it with `req.query.plaintext`. **How would I send the English?** [place your function url here]&plaintext=[insert the English]

:question: How do I use the Morse Code package?
**Tip**: Try reading the [documentation](https://www.npmjs.com/package/morse-code-converter) first. ```js const morse = require("morse-code-converter"); const code = morse.textToMorse('Hey how are you?'); // .... . -.-- .... --- .-- .- .-. . -.-- --- ..- ..-.. const text = morse.morseToText(code); // HEY HOW ARE YOU? ```

:bulb: Be sure to return the code in the body of the response!

:question: Um. Body?
**Tip**: `context.res` is the object you use to return a response to the user. ```js context.res = { body: [insert your encoded English here] }; ```

:exclamation: Don't forget to git pull before making any changes to your local repo!!

Remember: we test your Morse Code function everytime you commit!