serverless-camp-2's People
serverless-camp-2's Issues
Getting Started with Serverless
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.
✅ Tasks:
- 1: Optional: complete the get started with GitHub guide.
- 2: Create a new branch named
test
. - 3: Add a paragraph introducing yourself under the
About Me
section in theblog.md
file in root. - 🚀 Commit the change to
test
, make a pull request to your main branch, naming itAdding self introduction
and add a detailed description of your contribution. Then merge the pull request.
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 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!
Key functions you should be familiar with after this task include:
- Committing changes
- Forking a repository
- Making a new branch
- Making a pull request
One cat, two cats, red cat, blue cat
Week 1 Step 6 ⬤⬤⬤⬤⬤⬤◯◯◯ | 🕐 Estimated completion: 25-35 minutes
Trying to make node-fetch happen
✅ Task:
- Run
git pull
and create a new branch calledtwocatz
- 1: Create and deploy an HTTP trigger Azure Function that creates a request for an image from the CataaS API
- 2: Return the image in the request body encoded in base64 in JSON format
- 🚀 Place your function URL in a repository secret called
TWOCATZ_ENDPOINT
and commit function code in a file namedtwocatz/index.js
to thetwocatz
branch - 🚀 Create a pull request that merges
twocatz
tomain
, but do not merge it
Note: Every time you make a new commit to twocatz
, 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..."
}
1: Making requests in Azure
To make a request to the CataaS API, you can try using the node-fetch
module, but there are many other ways to do it as you can see here.
❗ How can I make a request to the CataaS API?
Let's use the node-fetch
module for this task.
❗ Make sure you are in the directory of your Azure function to run these commands.
-
Install the module in terminal using the following commands in order:
npm init -y npm install node-fetch
-
Add it to your code:
Add this line of code to reference the module at the top of your code (outside of the function):
const fetch = require('node-fetch')
-
Make the request!
Add the following code within the function:
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
-
What should you place in place of
THE_ENDPOINT
? Change the code.
2: Return your images encoded in base64!
❗ What does it mean to encode something 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!
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:
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.
❗ How can I encode data in base64?
base64data = Buffer.from(originaldata).toString('base64')
//put what you want to turn into base64 inside "originaldata"
//"originaldata" will be encoded in base64.
For fun: Once your API successfully returns the images in base64, you can see what they look like using this website.
❗ Now that I've got the picture in base64, how do I return it?
context.res
is the key to answering this question!
context.res = {
body: { your_picture_in_base64 }
}
You need to put brackets to return the data in json format.
Getting Emotional with APIs
Week 2 Step 1 ⬤◯◯◯◯◯◯◯ | 🕐 Estimated completion: 5-20 minutes
Getting Emotional ~ With the Face API
Because of amazing APIs, you don't need to be an expert in machine learning and AI to take advantage of cutting edge technology. In this project, we are going to be building an API and webpage to return you a GIF when you upload a picture of yourself!
✅ Task:
Create a request in Postman to send an image of a person to the Azure Face API to return the subject's emotions
- 1: Create a Face API Endpoint
- 2: Create a POST request in Postman to the Face API to retrieve the emotion attributes of this image
- 🚀 Place the API endpoint and subscription key in the GitHub repository secrets:
API_ENDPOINT
ANDSUBSCRIPTION_KEY
- 🚀 Comment the output of your Postman request to move on
🚧 Test your Work
You should get the following expected output if you have configured your Face API correcty, as well as sent the request with the correct parameters and body.
✅ Expected Output
{
"result": [
{
"faceId": "d25465d6-0c38-4417-8466-cabdd908e756",
"faceRectangle": {
"top": 313,
"left": 210,
"width": 594,
"height": 594
},
"faceAttributes": {
"emotion": {
"anger": 0,
"contempt": 0,
"disgust": 0,
"fear": 0,
"happiness": 1,
"neutral": 0,
"sadness": 0,
"surprise": 0
}
}
}
]
}
1. The Face API
The Face API will accept the image and return information about the face, specifically emotions. Watch this video on Microsoft Cognitive Services for an in-depth explanation: http://www.youtube.com/watch?v=2aA8OEZ1wk8
❓ How do I create and access the Face API?
- Log into your Azure portal
- Navigate to Create a Resource, the AI + Machine Learning tab on the left, and finally select Face and fill out the necessary information
- Record and save the API endpoint and subscription key
- Place the API endpoint and subscrition key in the GitHub repository secrets:
API_ENDPOINT
ANDSUBSCRIPTION_KEY
- These keys will be used in the Azure function to give access to this API
❓ Where can I find the Face API keys?
- Navigate to the home page on the Micrsoft Azure portal (https://portal.azure.com/#home)
![Screen Shot 2021-02-04 at 4 00 33 PM](https://user-images.githubusercontent.com/28051494/106971033-edac0000-6702-11eb-8243-1b5c2318f76d.png)
- Click on the resource you need the keys for
![Screen Shot 2021-02-04 at 4 00 49 PM](https://user-images.githubusercontent.com/28051494/106971035-ef75c380-6702-11eb-965b-c3ef7b5a7574.png)
- On the left menu bar, locate the Resource Management section and click on "Keys and Endpoint"
![Screen Shot 2021-02-04 at 12 26 36 PM](https://user-images.githubusercontent.com/28051494/121618965-986b5c80-ca1c-11eb-8216-bd7347fb359a.png)
2. Using Postman to Send a Request
Now, we can test if our API is working using Postman. Make sure to pay close attention to the documentation and the API Reference
Request URL
Request URL is used when a web client makes a request to a server for a resource. Notice that the request url listed in the API reference is this:
https://{endpoint}/face/v1.0/detect[?returnFaceId]\[&returnFaceLandmarks]\[&returnFaceAttributes]\[&recognitionModel]\[&returnRecognitionModel][&detectionModel]
Parameters
Parameters are typically used in requests to APIs to specify settings or customize what YOU want to receive.
❓ What are the parameters for the request?
The Request URL has the following parameters in [ ]:
- [?returnFaceId]
- [&returnFaceLandmarks]
- [&returnFaceAttributes]
- [&recognitionModel]
- [&returnRecognitionModel]
- [&detectionModel]
Important things to note:
- All of the bracketed sections represent possible request parameters
- Read through Request Parameters section carefully
- How can we specify that we want to get the emotion data?
- All of the parameters are optional
- We can delete the parameters we don't need in our request
- Your request URL only requres one parameter, with a specific value
- Between
detect
and your parameter, add?
- If you had more than one parameter, you would need to place
&
between each (but not betweendetect
and your first parameter)- Since we only have one parameter, no
&
are needed
- Since we only have one parameter, no
💡 All of this is located in the documentation! Find this section to read more:
Request Headers
Request Headers tell the receiving end of the request what type of data is in the body.
❓ How do I specify Request Headers?
- Go back to the Face API documentation here, and find the Request headers section.
- The
Content-Type
header should be set toapplication/octet-stream
. This specifies a binary file. - The
Ocp-Apim-Subscription-Key
header should be set to one of your two keys from your Face API resource. - Request headers are not part of the request URL. They are specified in the Postman headers tab:
- The
Request Body
The body of a POST request contains the data you are sending.
❓ How do I send the image in the body of the POST request?
Go to the body tab of your Postman request and select binary:
![Screen Shot 2021-05-27 at 6 37 53 PM](https://user-images.githubusercontent.com/70852990/119905640-a7311a00-bf1a-11eb-8b39-d891638e5e42.png)
Next, just upload the image and send your POST request.
[TOP SECRET] Please open
Week 1 Step 8 ⬤⬤⬤⬤⬤⬤⬤⬤◯ | 🕐 Estimated completion: 5-15 minutes
[TOP SECRET] Morse Code Converter
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:
- Run
git pull
and create a new branch calledmorse
- 1: Install the
morse-code-converter
package - 2: Code an HTTP trigger function named
morse
withmorse-code-converter
that takes in English as a parameter and outputs it in Morse Code - 🚀 Place the function URL of your new Morse Code HTTP Trigger as a repository secret named
MORSE_ENDPOINT
and commit your function's code to a file namedmorse/index.js
to themorse
branch - 🚀 Create a pull request that merges
morse
tomain
, but do not merge it
❗ Do not merge the branch!!
1: 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.
❓ 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
.
❓ How do I install the package?
In the left tab, scroll down to Console:
Enter these commands in order:
npm init -y
npm install morse-code-converter
❗ 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](https://user-images.githubusercontent.com/28051494/116067063-a6684800-a63d-11eb-9652-fbda8805fd8a.png)
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](https://user-images.githubusercontent.com/28051494/116066822-525d6380-a63d-11eb-9cea-5f2b82807cca.png)
📚 Reminder: don't forget to import your package!
const morse = require("morse-code-converter");
💡 Make sure your parameter is named
plaintext
2: Using morse-code-converter
❓ How do I receive the English as a parameter?
Query parameters can be accessed from the req
object in the input of the module.exports
function.
💡 Since ours is named
plaintext
, we can access it withreq.query.plaintext
.
How would I send the English?
[place your function url here]&plaintext=[insert the English]
❓ How do I use the Morse Code package?
Tip: Try reading the documentation first.
const morse = require("morse-code-converter");
const code = morse.textToMorse('Hey how are you?'); // .... . -.-- .... --- .-- .- .-. . -.-- --- ..- ..-..
const text = morse.morseToText(code); // HEY HOW ARE YOU?
💡 Be sure to return the code in the
body
of the response!
❓ Um. Body?
Tip: context.res
is the object you use to return a response to the user.
context.res = {
body: [insert your encoded English here]
};
❗ Don't forget to git pull
before making any changes to your local repo!!
Remember: we test your Morse Code function everytime you commit!
Open up!
Week 1 Step 4 ⬤⬤⬤⬤◯◯◯◯◯ | 🕐 Estimated completion: 35-45 minutes
Building our first function ⚡[HackerVoice]
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.
✅ Tasks:
- Run
git pull
and create a new branch calledhackervoice
- 1: Create an Azure account
- 2: Set up Azure locally on VS Code
- 3: Create an HTTP trigger Azure function that gets content from a request parameter called
password
and returns it in the function's body - 4: Test your function locally with Postman and, when you confirm that it works, deploy your function
- 🚀 Place your function URL in a repository secret called
HACKERVOICE_ENDPOINT
and commit the function's code in a file namedhackervoice/index.js
on thehackervoice
branch - 🚀 Create a pull request that merges
hackervoice
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: Create an Azure Account
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.
- This is only for security purposes (preventing multiple free accounts per person).
- You won't be charged unless you choose to buy a premium account, which we do not need for this course.
Set Up Azure Locally on VS Code
- Confirm if you have installed the Azure Tools extension on VS Code
- Create your local project
- ❗ When prompted to set the language, choose JAVASCRIPT not C#)
- ❗ When prompted for the Authorization level, always choose
Function
- Run the function locally
- Publish the project to Azure
- Get your function url the Output window in VS Code
- Test the function on Postman
❓ What should running the function look like?
Start the debugger by going to index.js and then pressing the F5 key.
Having trouble with Azure Tools? Try installing it this way
Once you receive the localhost link in the terminal, follow it and notice the terminal log "Executing 'Functions.[Name of your function]'" indicating that you made a request to the function.
If the request is successfully made in Postman this is what it should look like:
Once you deploy/publish the code to Azure successfully, you will get the function url in the Output of VS Code:
3: Create your own HTTP Trigger Function
You should see the HTTP Trigger Function template code Microsoft Azure starts you with when you first create your trigger.
❗ What is happening in index.js?
- 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:
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.";
- Results of that conditional ternary statement are assigned to
responseMessage
which is returned in the function body
Now, let's begin coding by modifying that template. First, you will need to retrieve content from a request parameter named password
. Recall that parameters look like this in a full URL:
www.mywebsite.com/api/endpoint?param1=hi¶m2=hi
❗ How to get content from a request parameter?
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.
- 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
- You 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>;
//example:
let color = req.query.color;
If the user makes a request with a parameter of <url>?color=blue
then the variable color in your function will hold that value.
Note: your parameter must be named
password
Finally, we have to return something to the users. In this case, we will be returning the value of the request parameter we just retrieved.
❗ How can I return something in the function body?
In Azure, context
is an object that holds data about the response of the HTTP function. Read more about Accessing the request and response.
In our HTTP trigger function, we have defined context object with the body property:
context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
To return the password in body, simply replace responseMessage
with password
.
4. Test your Function with Postman
- Deploy your function to Azure
- Get your function url from the Output window on VS Code(same as before) and make a request on Postman
- Add a parameter with the key
password
and give it any random value - Make sure that your function is returning the
password
parameter in the body
🚀 Add Repository Secrets
❗ How do I add a respository secret?
A Song 4 U
Week 2 Step 6 ⬤⬤⬤⬤⬤⬤◯◯ | 🕐 Estimated completion: 10-15 minutes
Pose! Song Recommendation with Age Recognition
✅ Task:
Create a new Azure Function that parses a Twilio request body and returns the image url.
- Create a new branch called
song4u
- 1. Create a Twilio account
- Install npm package
querystring
- 2. Create a new Azure Function called
song4u
that acts as a Twilio webhook - 3. Return the image url from the POST request
- 🚀 Commit your updated function code to
song4u/index.js
on thesong4u
branch and add your function url to a repository secret namedSONGREC_ENDPOINT
- Create a pull request that merges
song4u
tomain
, but do not merge it
🚧 Test Your Work
To test your work, try texting a jpg image to your Twilio number. You should receive a link back that contains the image.
❓ How do I find my Twilio number?
See your phone numbers.
1. Creating a Twilio Account
In this project, the user will text an image to a Twilio number and an Azure function will analyze the image. The Face API will determine the age of the person in the image. We need to create a Twilio account first so that the user can text an image to your Twilio number.
Sign up for a free Twilio trial account here.
❓ What's the process like for signing up for Twilio?
-
When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
-
Once you verify your number, you'll be asked a series of questions to customize your experience.
-
Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.
Learn more about it here!
After we get our account set up, we need to get a phone number, which is free from your trial account.
❓ Where can I get a phone number?
-
Create a new project on Twilio.
-
Add a brand new number for your Twilio project, which will be used to send texts to users. Save this to use for later.
Before you move on, be sure to create a new Azure function!
2. Configuring the Azure Function
Our new Azure function will act as a Twilio webhook.
💡 A Twilio webhook is the endpoint that will receive a POST request whenever a Twilio number is used or a text is sent. Twilio sends an HTTP request to a webhook whenever something happens (such as when a text is sent).
You will need to place your function's URL into the settings on your Twilio account.
Do you like the command line more? Try using the Twilio CLI instead!
❓ How do I configure it?
- Go to the Twilio Console's Numbers page
-
Click on the phone number you'd like to modify
-
Scroll down to the Messaging section and the "A MESSAGE COMES IN" option.
-
Paste in your Azure Function URL. Make sure to click
Save
afterwards!!
3. Coding the Azure Function
Test the webhook out!
If you want more insight into how a webhook actually works, try this:
❗ Log the request body in your console using `context.log(req.body)` and text your Twilio number.
Using this code:
module.exports = async function (context, req) {
var reqbody = req.body
context.log(reqbody)
context.res = {
// status: 200, /* Defaults to 200 */
body: reqbody
};
}
You might get something like this:
ToCountry=US&MediaContentType0=image%2Fjpeg&ToState=MI&SmsMessageSid=MM0fe83458b74a1f626eb0da4685ab28b5&NumMedia=1......
In order to parse the parameters from those values you just saw, we need an npm package.
📦 Install querystring
We need to install the npm package querystring
. This package parses query strings, and we will use it to parse the SMS sent by the user to the Twilio number so we can access the image sent in the text.
💡 You only need to use
npm init -y
if you are installing npm packages for the first time on an Function App!
As we did when we installed parse-multipart
, we need to enter npm init -y
(which initializes the package.json files) before we can install querystring
:
Now we can install querystring
by entering npm install querystring
:
❗ The parameter value you want to parse with
querystring
and return from the Azure Function in the body is calledMediaUrl0
.
Now, to use querystring
, first don't forget to initialize it!
const querystring = require('querystring');
Then, let's parse the request body, which is held in req.body
.
const queryObject = querystring.parse(req.body);
From this outputted object, we'll find its MediaUrl0
attribute and return it.
❓ How do I return the output?
context.res = {
body: queryObject.MediaUrl0
};
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.