Serverless Function API Calls

Is it possible to pass parameters and data back and forth between the FE and a serverless function?

We’re attempting to call a private API in the serverless function, and we were hoping we could set up an endpoint using serverless-express, but it looks like we probably need to use webpack for any packages outside a small handful of supported packages.

Wanted to confirm it’s even possible to use serverless-express with webpack in this way before attempting it.

Also, open to other ways of accomplishing the same thing. The main goal is to pass parameters to the serverless function and get json data back.

Hi @JLouis85 ,

I’m pretty sure you do not need serverless-express to expose an endpoint.

In your ‘serverless.json’ you can define the endpoints you want to expose with your serverless function. This could look something like this:

{
 "runtime": "nodejs12.x",
 "version": "1.0",
 "secrets": ["APIKEY"],
 "endpoints": {
 "randomgetmethod": {
 "method": "GET",
 "file": "randomgetmethod.js"
 },
 "randompostmethod": {
 "method": "POST",
 "file": "randompostmethod.js"
 }
 }
}

If you send a POST request to https://{domainName}/_hcms/api/randompostmethod you can pass it params or a body.

Let’s say I would send a POST request tohttps://{domainName}/_hcms/api/randompostmethod?param=test&secondparam=anothertest with some params, you can access those in the function like this:

exports.main = (context, sendResponse) => {
 const param = context.params.param[0]
 const secondParam = context.params.secondparam[0]

 // sendResponse is a callback function you call to send your response.
 sendResponse({ body: { message: `first param is ${param} and second param is ${secondParam}` }, statusCode: 200 });
};

You could Axios in your serverless function to make calls to your private API.

Thank you! We’ll test out your suggestion, and let you know if we have any more questions.

I am passing a variable ‘email’ in a query string parameter ( ExampleURL).

Within my functions file I am able to get portalid using context.params.portalid[0], as a test. Email, however does not return a value when using context.params.email[0]. Any suggestions?

Hi @bsha100 ,

Could you try the following URL instead? I had some issues in the past with getting the first param as well.

Thanks for the quick response @Teun, I have update the code to add ?random=test at the beginning of the query string varibles, however when I set console.log(context.params.email) in the endpoint, it is not updating. I added console.log(“TEST”), as well, and am not getting any updates with calls to hs logs in the CLI. Is there some sort of caching mechanism? Calling the endpoint directly shows the update, so I’m wondering if the call from the HTML file is breaking. Here is the code. I have replaced the portal ID with x’s.
test_form.html

<!--

templateType: page

isAvailableForNewContent: true

label: Submission Test Form

-->

<!doctype html>

\<html>

    \<head>

        \<meta charset="utf8">

        \<title>{{ content.html\_title }} Page\</title>

        \<meta name="description" content="{{content.meta_description}}">

            {{standard\_header\_includes}}

        \<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">\</script>

        \<script>

                $(window).on('load', function(){

                    email = '';

                    apicall = '';

                    setTimeout(function () {

                        $("input\[name='email']").blur(function(){

                            email = $("input\[name='email']").val();

                          //  alert(email);

                        });

                    }, 1000);

                });

                bodyFormData = new FormData();

                var requestOptions = {

                'method': 'GET',

                'headers': {

                'Content-Type': 'application/json',

                },

                };

                fetch("[http://xxxxxxxx.hs-sites.com/\_hcms/api/test?random=n&email=](http://xxxxxxxx.hs-sites.com/_hcms/api/test?random=n&email=)"+email+"&portalid=xxxxxxxx", requestOptions)

            .then(response => response.text())

            .then(result => console.log(result))

            .catch(error => console.log('error', error));

        \</script>

    \</head>

    \<body>

        \<h1>EMAIL TEST\</h1>

        {% module "page\_template\_logo" path="@hubspot/logo" label="Logo" %}

        {% module "page\_template\_rich\_text" path="@hubspot/rich\_text" label="Rich\_text" %}

        {% module "page\_template\_form" path="@hubspot/form" label="Form" %}

        \<div>

        \</div>

        {{standard\_footer\_includes}}

    \</body>

\</html>

serverless.json

{

“runtime”: “nodejs12.x”,

“version”: “1.0”,

“environment”: {},

“endpoints”: {

"test": {

   "file": "test.js",

   "method": "GET"

}

},

“secrets”: [“hapikey”]

}

@Teun, inexplicably, the form is submitting correctly again, however I am still not getting a value for ‘email’. The url I am using as the endpoint is structured like this currently.
http://xxxxxxxx.hs-sites.com/_hcms/api/test?random=n&email=bob@gmail.com&portalid=xxxxxxxx
I am random is coming out as ‘n’ when using console.log(context.params.random[0]) , however email is still coming out blank.

@Teun, I figured it out. I was defining the variable inside a function. Putting the fetch() call within the function solved the problem. Thanks for your input and the solution, which did work once I realized my mistake.