Build a new function Random Number Generator
Random Number generator
exports.handler = (event, context, callback) => {
let min = 0;
let max = 10;
let generateNumber = Math.floor(Math.random() * max) + min;
callback(null, generateNumber);
};
No JSON needed
The Math.floor() function returns the largest integer less than or equal to a given number.
Note: Math.floor(null) returns integer 0 and do not give a NaN error.
The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
Create an API connecting the function called randomnumbers
Use REST and New API
Next step would be to create a resource for the API - resource called random
Add a GET Method and hit the check mark
Attach a Lambda function the the GET Method
Click TEST to test the API Get Method
Now test the API
| |
The response body shows the results of the random number generator
the Status 200 states that the http call was successful
the next step is to deploy the API which will create an accessible URL
The Stage name will be prod
The deployment creates an endpoint via URL address string
The GET method contains the URL link
random number generator
Next we will be passing name pair values to functions using the URL
BY USING ? AFTER URL
Now we will edit the Integration Request
We need to define input variables adding a body mapping template to the Integration Request
Build a querystring for the function
{
"min": $input.params('min'),
"max": $input.params('max')
}
Change the randomNumberGenerator function to use the event parameters
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
console.log('Starting Function');
exports.handler = (event, context, callback) => {
let min = event.min;
let max = event.max;
let generateNumber = Math.floor(Math.random() * max) + min;
callback(null, generateNumber);
};
Redeploy and pass parameters via the URL String
https://2ntt48niz6.execute-api.us-east-1.amazonaws.com/prod/random?min=1&max=10
|
No comments:
Post a Comment