---
schema_version: "1"
id: 3b8fd70782ebceb6e85c223f7a9943d14219b19c0f12e479cd5d32fb0e46ab7d
title: Invoke Functions with Apex
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/salesforce-functions/functions/guide/dev-guide/invoke-apex.md
canonical_url: https://developer.salesforce.com/docs/platform/functions/guide/invoke-apex.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: b1e331ef95d7d5412b7f58228e83820bd897eba837b24fb9d3559a40486ea29b
products:
  - Salesforce Functions
---
# Invoke Functions with Apex

Salesforce Functions only run when invoked. When none are invoked, the function rests in an idle state and elastically scales down to use minimal system resources. Functions can be invoked directly from a Salesforce org via Apex. The function and project must be deployed to a compute environment connected to the org, as described in [Deploying a Function](https://developer.salesforce.com/docs/platform/functions/guide/deploy.md).

You can use Apex to invoke your functions synchronously or asynchronously. Functions can be invoked from anywhere you can use Apex code. So, for example, you could invoke or asynchronously queue your function within workflows that use [Apex Actions in Flow](https://help.salesforce.com/articleView?id=flow_ref_elements_apex_invocable.htm&type=5), [Batch Jobs](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm), [Apex Triggers](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm), or [Apex Platform Event Subscriptions](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_subscribe_apex.htm).

Use classes in the `functions` Apex namespace to find and invoke deployed functions. Reference documentation for the Apex `functions` namespace and classes is available in the [Apex Reference Guide: Functions Namespace](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_namespace_functions.htm).

## Deploy Your Apex Code

Deploy your Apex code to your scratch org using the following command:

```sh
sf project deploy start --target-org MyScratchOrgAlias
```

**tip:** In VS Code, from the Command Palette, choose **SFDX: Push Source to Default Scratch Org**.

## Get Function Reference

A function's org can be `public` and only access references within a namespace, or a function's org can be `global` and access references across multiple namespaces.

Retrieve a `public` reference to a deployed function by using the name of the function and its project. Using the `functions.Function.get()` method, pass the project and function in a single string of the format “MyProject.myfunction” to retrieve references within the same namespace. For example, to retrieve the "GeneratePDF" function in the "Onboarding" function project, use "Onboarding.GeneratePDF".

The following Apex example gets a reference within a namespace to the AccountFunction deployed as part of the MyProject project:

```java
functions.Function accountFunction = functions.Function.get('MyProject.myfunction');
```

**note:** Leaving out the namespace defaults to the org the function is in. Accessing references across namespaces in a `public` org results in error messages.

Retrieve a `global` reference to a deployed function by using the name of the function, its project, and the unique id of the namespace where the reference is. Similarly, using the `functions.Function.get()` method, pass the project, function, and namespace to retrieve references from across namespaces.

The following Apex example gets a reference to the AccountFunction from the MyNamespace namespace, deployed as part of the MyProject Project:

```java
functions.Function accountFunction = functions.Function.get('MyNamespace','MyProject.myfunction');
```

### Use Synchronous Invocation

Use `Function.invoke(payload)` to invoke your function synchronously. The function invokes with the payload you provide, and response data and results are returned from the `invoke()` call in a `FunctionInvocation` instance.

For synchronous invocations, you have a maximum limit of 2 minutes for your function to run and complete. If your function requires more than 2 minutes to complete, consider using asynchronous invocation instead. Apex triggers must be called asynchronously. If you can't use asynchronous invocation, see [Limits](https://developer.salesforce.com/docs/platform/functions/guide/limits.md) for other approaches.

The following example synchronously invokes the accountFunction reference:

```java
functions.FunctionInvocation invocation = accountFunction.invoke('{ "accountName" : "Acct", "contactName" : "MyContact", "opportunityName" : "Oppty" }');
String jsonResponse = invocation.getResponse();
System.debug('Got response ' + jsonResponse);
```

### Use Asynchronous Invocation

Invoking a function directly through Apex is similar to making an Apex callout. If your function takes longer than 2 minutes to return, the request times out. To avoid time outs consider invoking your function asynchronously, using the asynchronous `Function.invoke(payload, callback)` method rather than the `Function.invoke(payload)` synchronous method. Provide an Apex callback class that implements `functions.FunctionCallback` in your call to `Function.invoke(payload, callback)`.

Calling `Function.invoke(payload, callback)` queues your function to be invoked through asynchronous Apex. When your queued function is invoked, your Apex callback's `handleResponse()` method is called with the invocation results. Your method processes the `FunctionInvocation` results, which could include actions such as modifying org data, sending [platform events](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_publish_apex.htm), or sending [custom notifications](https://help.salesforce.com/articleView?id=notif_builder_custom.htm&type=5). If the function invocation fails, error information is provided in the `FunctionInvocation` results.

The following example invokes a function asynchronously and uses a FunctionCallback class to handle the invocation results:

```java
public with sharing class FunctionApex {
    public static void test() {
        functions.Function myFunction = functions.Function.get('MyProject.myfunction');
        // Pass a callback to Function.invoke to perform an asynchronous invocation.
        functions.FunctionInvocation invocation = myFunction.invoke('{"fields":["Id","Name"]}', new DemoCallback());
    }

    public class DemoCallback implements functions.FunctionCallback {
        public void handleResponse(functions.FunctionInvocation result) {
            // Handle result of function invocation
            String jsonResponse = result.getResponse();
            System.debug('Got response ' + jsonResponse);

            // Log error, if applicable
            if (result.getStatus() == functions.FunctionInvocationStatus.ERROR) {
                functions.FunctionInvocationError resultError = result.getError();
                if (resultError != null) {
                    System.debug('Error type: ' + resultError.getType());
                    System.debug('Error message: ' + resultError.getMessage());
                } else {
                    System.debug('Error: UNKNOWN');
                }
                return;
            }
            // Successful response, deserialize the response to an Apex object.
            JSONParser parser = JSON.createParser(jsonResponse);
            Response response = (Response)parser.readValueAs(Response.class);
            // Verify that the Function actually wrote to the org.
            Account account = [ SELECT Name FROM Account WHERE Id = :response.accountId ];
            System.debug('Found account with name ' + account.Name);
        }
    }

    // A plain old data class to which we can deserialize the Function's response.
    public class Response {
        public String accountId;
        public String contactId;
        public String opportunityId;
    }
}
```

The Apex Callback runs as the user that invoked the function and runs in system mode.

Invoking a function asynchronously doesn’t count against asynchronous Apex limits, such as Apex Queueable limits.

To get the status of all pending functions invoked asynchronously, you can use a query on FunctionInvocationRequest similar to the following:

```sh
sf data query --query "SELECT Status, CreatedDate FROM FunctionInvocationRequest"
```

You can get the status for a specific asynchronous invocation by using the ID returned from `FunctionInvocation.getInvocationId()` as a filter on FunctionInvocationRequest:

```sh
sf data query --query "SELECT Status, CreatedDate FROM FunctionInvocationRequest WHERE Id = '<ID from getInvocationId()>'"
```

## Use Functions Standard Objects as Monitoring Tools

| Object Name                                                                                                                                  | Lets the user...                                                                                                                                                                                                                                            |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [FunctionInvocationRequest](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_functioninvocationrequest.htm) | <ul><li>Represent invocation information for a function.</li> <li>When using the Apex `functions.Function` invoke methods, a `FunctionInvocationRequest` record is created that contains information on the status and results of the invocation.</li></ul> |
| [FunctionReference](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_functionreference.htm)                 | <ul><li>Represent a deployed Salesforce Function associated with an org.</li> <li>Use as a read-only record to get information about a specific function associated with your org.</li></ul>                                                                |
| [FunctionConnection](https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_functionconnection.htm)               | <ul><li>Represent a connection between an org and Salesforce Functions.</li> <li>Use as a read-only object that shows the current connection information between your org and Salesforce Functions.</li></ul>                                               |
