# Hello World example using functions

## Overview

This guide provides step-by-step examples for running a function from a custom app and an automation in Rippling.

## Custom app - custom object detail view

In this example, we're going to build a function that consolidates three actions into one, which streamlines the sign-up process for the end user. They will only need to perform a single action and will not be required to enter information (e.g., name) that was previously collected and already exists in Rippling.

We can do this by by calling the function from the list or detail view of a custom object. Here we have a custom app called Class Manager that allows employees to sign up for training classes.

The current process for signing up for a class is for the user to select the class, click the Add Class Signup button, and manually enter their information to create a sign up record.

![Add Class Signup](https://developer.rippling.com/assets/images/AddClassSignupButton-b932d2d864ae2be9f1031a7ae6005dd7.png)

![Add Class Signup](https://developer.rippling.com/assets/images/AddClassSignup-b7ceeaabcc6e70322fabf6b26d783fbb.png)

We can use a function to make this process quicker and more seamless for the user. Let's start by instantiating the Rippling Javascript SDK and adding our bearer token. The token is saved in our **custom settings**, so we can access it using the following code:

```text
const token = context.settings["my_api_key"];
const ripplingSDK = new RipplingSDK({ bearerToken: token });
```

Next, let's add the logic for creating the class signup record. We can do this by creating an HTTP request to the custom objects endpoint.

```text
const signupResponse = await ripplingSDK.customObjects.records.create("class_signup__c", {"owner_role": event.current_user, "class__c": event.record_id});
```

We need to send parameters in our request to let the API know what information to include in the class sign up record. The first parameter is the _custom object API name_. We can find this by looking at the **custom object**.

![Custom Object API Name](https://developer.rippling.com/assets/images/CustomObjectAPIName-916065752655225a7e3eeb920515e6a6.png)

The second parameter is a JavaScript object with a list of key value pairs that match the field API names in our custom object. This list tells the API what values to assign to the fields in the new class sign up record. These can be found under the **Fields** tab in the **custom object**.

![Add Action](https://developer.rippling.com/assets/images/FieldAPINames-052354f8cb47fad480b38d40094c1546.png)

We want to pass in the user and the class information, and we can find both in the `FunctionEvent`. `event.current_user` gives us the logged in user and `event.record_id` gives us the ID for the class that is currently selected.

It's also a good idea to add some logging here in case we need to see the response from the API for testing or troubleshooting.

```text
console.log(JSON.stringify(signupResponse))
```

Now that the logic is in place, we can indicate how we want the function to respond to the user's input. If the user is signed up successfully, we want to display a success message. The message can be customized here, and the 200 response code will make the message appear in a green box.

```text
return new FunctionResponse({
  body: {},
  statusCode: 200,
  headers: {},
  message: "You successfully signed up!",
});
```

If there is an error, the user will see a red box with a generic failure message. We can customize this response by adding error handling to our function. Here we are returning a custom error message and logging the error returned from the API.

```text
try{
  const signupResponse = await ripplingSDK.customObjects.records.create("class_signup__c", {"owner_role": event.current_user, "class__c": event.record_id});
  console.log(JSON.stringify(signupResponse))
}
catch(error){
  console.log(error);

  return new FunctionResponse({
  body: {},
  statusCode: 400,
  headers: {},
  message: "Something went wrong.",
});
}

return new FunctionResponse({
  body: {},
  statusCode: 200,
  headers: {},
  message: "You successfully signed up!",
});
```

Put it all together and here's our completed function!

```text
import RipplingSDK from "rippling-sdk";
import _ from "lodash";
import {
  FunctionContext,
  FunctionEvent,
  FunctionResponse,
} from "rippling-function-types";

export async function onRipplingEvent(
  event: FunctionEvent,
  context: FunctionContext
) {

  // Instantiate the Rippling SDK with authentication
  const ripplingSDK = new RipplingSDK({ bearerToken: "sinGe..." });
  
  try{

    // Create a new Class Signup for the running user.
    const signupResponse = await ripplingSDK.customObjects.records.create("class_signup__c", {"owner_role": event.current_user, "class__c": event.record_id});

    // Log the successful API response
    console.log(JSON.stringify(signupResponse))
  }
  catch(error){

    // Log the error returned from the API
    console.log(error);

    // Return a custom error response to the user
    return new FunctionResponse({
    body: {},
    statusCode: 400,
    headers: {},
    message: "Something went wrong.",
  });
  }

  // Return a custom success response to the user
  return new FunctionResponse({
    body: {},
    statusCode: 200,
    headers: {},
    message: "You successfully signed up!",
  });
}
```

To use the function, we need to assign it to an action. We can add an action from our custom object, and select our function. Since we want to only sign the user up for the class that is selected, we choose detail view for the visibility preference.

![Add Action](https://developer.rippling.com/assets/images/AddActionExample-454a1815f089bf8aa77c6adb4a5a8e62.png)

Now, our function will be run when the user selects the **Sign up** action from the Class Manager app.

![Signup Action](https://developer.rippling.com/assets/images/SignupAction-87141d54105bbb8b7118975c4bf53c80.png)

It went through successfully, so we can see our custom success message and a new record in class signups.

![Success](https://developer.rippling.com/assets/images/SuccessResponse-519179d5b5efca51f098fbd4c428d6d4.png)

This class has a rule that limits the number of signups to three students. Since we were the third signup, we will get an error if we click sign up again.

![Error](https://developer.rippling.com/assets/images/ErrorResponse-ce671a46579087f97bf649eda015cae0.png)

If we click **View** in the error message, we can see the details of the error in the **Execution log**, because we logged the error in the console.

![Error Log](https://developer.rippling.com/assets/images/ErrorLog-3649e1da2ab29b8ba7c762187794101f.png)

## Automation

We can also trigger a function from an automation to further automate repeated tasks. For example, when someone signs up for a class, we can reduce the available seats by one.

Let's start by writing a function. We need to first instantiate an instance of the Rippling SDK using our bearer token. The token is saved in our **custom settings**, so we can access it using the following code:

```text
const token = context.settings["my_api_key"]
const ripplingSDK = new RipplingSDK({ bearerToken: token });
```

Next, we need to grab the `record_id` from the event parameters. In this case, the event will be the creation of a class signup, and we will pass in the `record_id` of the class from the automation.

```text
const recordId = event.parameters?.record_id;
```

We can then use the `record_id` to retrieve the custom object record for the class.

```text
const classRecord = await ripplingSDK.customObjects.records.retrieve("class__c", recordId);
```

Next, let's grab the current number of available seats from the class record and create a variable to hold the updated seat count.

```text
const currentSeats = Number(classRecord.available_seats__c);
const updatedSeats = currentSeats - 1;
```

Now, we need to use the Rippling SDK to update the class record with the updated seat count.

```text
await ripplingSDK.customObjects.records.update("class__c", recordId, {
  available_seats__c: updatedSeats,
});
```

Lastly, let's add **validations, logging, and our function responses**.

The completed function looks like this:

```text
import RipplingSDK, {
  FunctionContext,
  FunctionEvent,
  FunctionResponse,
} from "@rippling/rippling-sdk";

export async function onRipplingEvent(
  event: FunctionEvent,
  context: FunctionContext
) {

  // Initialize an instance of the Rippling SDK
  const token = context.settings["my_api_key"]
  const ripplingSDK = new RipplingSDK({ bearerToken: token });
  
  // Grab the record_id from the event parameters
  const recordId = event.parameters?.record_id;

  // Return an error if the record_id is not set 
  if (!recordId || typeof recordId !== 'string' || recordId.trim().length === 0) {
    return new FunctionResponse({
      statusCode: 400,
      message: "Missing required parameter: record_id",
      body: {},
      headers: {},
    });
  }

  try {

    // Retrieve the class object record using the record_id
    const classRecord = await ripplingSDK.customObjects.records.retrieve("class__c", recordId);

    // Grab the current available seats and return an error if invalid
    const currentSeats = Number(classRecord.available_seats__c);
    if (isNaN(currentSeats) || currentSeats <= 0) {
      return new FunctionResponse({
        statusCode: 400,
        message: "Invalid seat count in class record.",
        body: {},
        headers: {},
      });
    }

    // Set the updated seat count
    const updatedSeats = currentSeats - 1;

    console.log(`🔄 Updating seats: ${currentSeats} → ${updatedSeats}`);

    // Update the class object with the updated seat count
    await ripplingSDK.customObjects.records.update("class__c", recordId, {
      available_seats__c: updatedSeats,
    });

    console.log(`✅ Successfully updated class record ${recordId}`);
    console.log(`📈 Seat count changed: ${currentSeats} → ${updatedSeats}`);

    return new FunctionResponse({
      statusCode: 200,
      message: "Successfully updated available seats.",
      body: {},
      headers: {},
    });
  } catch (error: any) {
    console.error("Failed to update class record:", error);

    return new FunctionResponse({
      statusCode: 500,
      message: "Failed to update available seats.",
      body: { error: error?.message ?? "Unknown error" },
      headers: {},
    });
  }
}
```

Once we **Save and Deploy** the function, it will be available to call from an automation.

To do this, select **Tools > Automation Studio** from the sidebar, and click **Create automation**.

After providing a name and description, we can set our automation trigger. We want this automation to be triggered when a new class signup is created.

![Automation trigger](https://developer.rippling.com/assets/images/WorkflowTrigger-9001da6e83f113eb97a2485fcf531a1b.png) ![Custom object trigger](https://developer.rippling.com/assets/images/CustomObjectTrigger-42fa90fadd4782eed337d48438f51c2a.png)

Next, we need to assign a variable to be passed into our function, so let's drag the **Assign value to a variable** step into our automation.

We need to create a variable to hold the **Class ID**, since that's the value our function is expecting.

![Add automation variable](https://developer.rippling.com/assets/images/AddWorkflowVariable-c44ec5378482bb1d211da03f69f1bfa3.png)

Once the variable has been saved, it can be assigned to a value. Click the **Insert automation variables** button and select the _ID_ from the _Class_ custom object.

![Automation variable](https://developer.rippling.com/assets/images/WorkflowVariable-d1dc03faed8e47f69138fa121b3df8a0.png)

Next, we want to call our function, so let's drag the **Run Function** step into our automation. Select the function we just created from the dropdown and **Add parameters**. It's imperative that the **Key** matches what the function is expecting. In this case, it is _record\_id_.

![Function record_id](https://developer.rippling.com/assets/images/FunctionRecordID-f4bd95a25d8d29c18bee0acaf6120a25.png) ![Run Function](https://developer.rippling.com/assets/images/WorkflowRunFunction-8ca2dc964e85debc65e5fc22a409185b.png)

We can click the **Insert workfow variables** button here to assign the _Class ID_ variable we created earlier.

![My variables](https://developer.rippling.com/assets/images/WorkflowMyVariables-56d33c54718ddf3609cb9daf4683ab29.png)

> 📝 **Note:** Make sure to delete any whitespace in the parameters textboxes to avoid it being included in your parameters.

![Remove whitespace](https://developer.rippling.com/assets/images/WorkflowWhitespace-b1129d759fd12ada87a1eba0154d7da8.png)

**Save and Publish** the automation, and verify that it is **Active**.

![Active automation](https://developer.rippling.com/assets/images/ActiveWorkflow-8f2546100b0a9e931f4837fe532cddb3.png)

Now, when a new class signup is created from our custom app, the number of available seats for that class will be reduced by one.

![Results](https://developer.rippling.com/assets/images/WorkflowResults-52d34894f742ae11b98a7cc7dc79844a.png)

## Resources

-   [Rippling API Docs](https://developer.rippling.com/documentation/rest-api)
-   [Rippling JavaScript SDK Docs](https://developer.rippling.com/documentation/js-sdk)
-   [Postman](https://www.postman.com/)
-   [Code Academy Javascript Tutorial](https://www.codecademy.com/learn/introduction-to-javascript)

Source: https://developer.rippling.com/documentation/rippling-platform/developer/functions/real-world-example

> For the complete documentation index, see [llms.txt](https://developer.rippling.com/llms.txt). Public pages have a Markdown version at the same URL with .md added.
