Cloudinary SDK: URL Helper

URL Helper Function

The URL Helper function will be configured as a GET and not take any input. This functions assumes you have an image asset with the public ID sample. This is very simple backend functionality that creates a URL for the sample asset.

Install cloudinary package from NPM

To begin using the Cloudinary SDK we need to install it from npmjs.org. First change directory into the hello-world directory where the app.js and package.json are located, and then npm install. (Note: when done installing from NPM, change directory back up to the root of the project).
cd hello-world
npm i cloudinary
The URL helper is a URL string generator. It takes information like public ID and transformation options and creates a URL.
Let's look at what we need to add to the template to implement this new function. We're adding the template.yaml we used for the Hello World function. We're adding the code to the app.js that we used for the HelloWorld function.
Code to add to template.yaml
This UrlHelper function, whose full name is UrlHelperFuction, definition should go under Resources with the original HelloWorldFunction. Notice that we changed the Handler to a new function called urlHelper. We also changed the Path to /url-helper.
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
UrlHelperFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.urlHelper
Runtime: nodejs12.x
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /url-helper
Method: get

Output Section

We need to add information that describes the output for the new function to the template. The full Output section is shown below. This will help to produce Output in the deployment that supplies the URLs needed to activate the functions with HTTP.
The UrlHelperApi defines the structure and variables for the new API. Note the path will be the same in the API as the Path defined in Resources.
https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/url-helper/
Outputs:
HelloWorldApi:
Description: API Gateway endpoint URL for Prod stage for Hello World function
Value:
Fn::Sub: https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/
HelloWorldFunction:
Description: Hello World Lambda Function ARN
Value:
Fn::GetAtt:
- HelloWorldFunction
- Arn
HelloWorldFunctionIamRole:
Description: Implicit IAM Role created for Hello World function
Value:
Fn::GetAtt:
- HelloWorldFunctionRole
- Arn
UrlHelperdApi:
Description: API Gateway endpoint URL for Prod stage for url helper function
Value:
Fn::Sub: https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/url-helper/
UrlHelperFunction:
Description: Url helper Lambda Function ARN
Value:
Fn::GetAtt:
- UrlHelperFunction
- Arn
UrlHelperFunctionIamRole:
Description: Implicit IAM Role created for url helper function
Value:
Fn::GetAtt:
- UrlHelperFunctionRole
- Arn

Add Code to app.js

First require in the cloudinary package and alias the cloudinary variable with version 2.
const cloudinary = require("cloudinary").v2;
Then export the urlHelper function. Be sure that all routes through the code return a response and JSON.stringify whatever object you return. When the Cloudinary SDK is successfully called, an object with an image key will be returned that is the full URL to request the sample image from Cloudinary.
exports.urlHelper = async (event, context) => {
try {
cloudinary.config();
const url = cloudinary.url("sample");
console.log(url);
return {
statusCode: 200,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
message: "hello world",
image: url,
}),
};
} catch (err) {
console.log(err);
return {
statusCode: 500,
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
error: err,
}),
};
}
};

Build the Package and Build the app

Now we can run the package command, followed by the build command.
sam package --template-file template.yaml --output-template-file package.yaml --s3-bucket my-bucket
sam build

Test the UrlHelperFunction Locally

When we invoke, we need to supply the name of the file that contains the Key/Value pairs for the environment variables.
The file we're storing the environment variables should be git ignored. It contains secret values and is shown below. We need to add the HelloWorldFunction because the environment variables are global and therefore expected with every function call.
{
"HelloWorldFunction": {
"CLOUDINARY_URL": "cloudinary://api_key:[email protected]_name",
},
"UrlHelperFunction": {
"CLOUDINARY_URL": "cloudinary://api_key:[email protected]_name",
}
}
Invoke the function locally. You can see the image URL,
http://res.cloudinary.com/cloud_name/image/upload/sample
is returned in a stringified object.
sam local invoke UrlHelperFunction -n config.json
Invoking app.urlHelper (nodejs12.x)
Fetching lambci/lambda:nodejs12.x Docker container image......
Mounting /Users/localuser/projects/aws2/first-sam-app/.aws-sam/build/UrlHelperFunction as /var/task:ro,delegated inside runtime container
START RequestId: 288bba21-a3fd-1260-1778-e461667c8dbf Version: $LATEST
2020-06-12T22:46:03.097Z 288bba21-a3fd-1260-1778-e461667c8dbf INFO http://res.cloudinary.com/pictures77/image/upload/sample
END RequestId: 288bba21-a3fd-1260-1778-e461667c8dbf
REPORT RequestId: 288bba21-a3fd-1260-1778-e461667c8dbf Init Duration: 995.58 ms Duration: 15.46 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 51 MB
{"statusCode":200,"headers":{"Content-Type":"application/json"},
"body":"{\"message\":\"hello world\",
\"image\":\"http://res.cloudinary.com/cloud_name/image/upload/sample\"}"}

Deploy

When testing is complete we can deploy. Since this function is in the same template as the already deployed HelloWorldFunction, we don't need to run the guided deploy. Execute the deploy command.
We do need to add parameters to the to samconfig.toml file to set the Environment variables. Notice that we have to escape the quoted Cloudinary URL string.
version = 0.1
[default]
[default.deploy]
[default.deploy.parameters]
stack_name = "cld-stack"
s3_bucket = "rptest-cld"
s3_prefix = "cld-stack"
region = "us-east-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
parameter_overrides = "CloudinaryUrl=\"cloudinary://api_key:[email protected]_name\""
Execute deploy.
sam deploy
When this function is complete, you'll can find the URL that can be used to execute the AWS function. The Output section of the build will show outputs for all functions defined in the template.
CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------
Outputs
---------------------------------------------------------------------------------------------------------------------------
Key UrlHelperdApi
Description API Gateway endpoint URL for Prod stage for url helper function
Value https://whd3754g79.execute-api.us-east-1.amazonaws.com/Prod/url-helper/
Key HelloWorldFunctionIamRole
Description Implicit IAM Role created for Hello World function
Value arn:aws:iam::697239927605:role/cld-stack-HelloWorldFunctionRole-1ESSBB2JLUIS5
Key UrlHelperFunctionIamRole
Description Implicit IAM Role created for url helper function
Value arn:aws:iam::697239927605:role/cld-stack-UrlHelperFunctionRole-BY12Z5KFTQ20
Key HelloWorldApi
Description API Gateway endpoint URL for Prod stage for Hello World function
Value https://whd3754g79.execute-api.us-east-1.amazonaws.com/Prod/hello/
Key UrlHelperFunction
Description Url helper Lambda Function ARN
Value arn:aws:lambda:us-east-1:697239927605:function:cld-stack-UrlHelperFunction-KBVPOSF5SVGW
Key HelloWorldFunction
Description Hello World Lambda Function ARN
Value arn:aws:lambda:us-east-1:697239927605:function:cld-stack-HelloWorldFunction-WLHH8OU16U1R
---------------------------------------------------------------------------------------------------------------------------
Successfully created/updated stack - my-stack in us-east-1
We can now make a postman, cURL or browser request to the UrlHelperAPI.
https://whd3754g79.execute-api.us-east-1.amazonaws.com/Prod/url-helper/
The functions returns the Hello message and the image URL per the function response.
Copy link
On this page
URL Helper Function