Invoke a Function From Apex

When your project is deployed, invoke your function from Apex.

Create an Apex Class

Make sure the current directory is your project root directory and use the following command to create an Apex class:

sf apex generate class --name FunctionApex --output-dir force-app/main/default/classes

tip: In VS Code from the Command Palette, choose SFDX: Create Apex class and enter the filename FunctionApex.

This command creates a FunctionApex.cls file with template code. Replace the contents of the file with the following Apex code:

public with sharing class FunctionApex {
    public static void test() {
        System.debug('Invoking myfunction');

        functions.Function myFunction = functions.Function.get('MyFunctionProject.myfunction');
        functions.FunctionInvocation invocation = myFunction.invoke('{"name":"MyAccount"}');
        String jsonResponse = invocation.getResponse();

        System.debug('Response from myfunction ' + jsonResponse);
    }
}

This class file invokes the function with a sample payload and prints the response.

Deploy Your Apex Code

Deploy your Apex code to your scratch org using the following command:

sf project deploy start --target-org MyOrgAlias

tip: In VS Code, from the Command Palette, choose SFDX: Push Source to Default Scratch Org.

Debug Apex Code Deploy

Deploying your Apex code with sf project deploy start can cause the following error:

PROJECT PATH                   ERRORS

─────────────────────────────────────────────── ──────────────────────────────────────────────

force-app/main/default/classes/FunctionApex.cls Type is not visible: functions.Function (5:9)

force-app/main/default/classes/FunctionApex.cls Type is not visible: functions.Function (6:51)

This error appears when the Apex class is running on API version 52.0 or earlier. To fix this issue, navigate to /force-app/main/default/classes/ and open the FunctionController.cls-meta.xml file. Edit the file to update the API version to 53.0 or later:

<?xml version="1.0" encoding="UTF-8" ?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>53.0</apiVersion>
    <status>Active</status>
</ApexClass>

Create a TraceFlag Record

Open the scratch org’s Developer Console to create a TraceFlag record. This record enables Apex debug logs in your scratch org and lets you execute apex log commands if needed.

sf org open --path /_ui/common/apex/debug/ApexCSIPage

Now, invoke your Apex code to execute your function:

Linux/OSX

echo "FunctionApex.test();" | sf apex run --file /dev/stdin

Windows

echo "FunctionApex.test();" | sf apex run

The output looks something like this:

Compiled successfully.
Executed successfully.

52.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;NBA,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WAVE,INFO;WORKFLOW,INFO
Execute Anonymous: FunctionApex.test();

...

18:20:51.102 (286350229)|METHOD_ENTRY|[6]||functions.Function.invoke(String)
18:20:51.102 (741953038)|FUNCTION_INVOCATION_REQUEST|[31]|Function.invoke[Name=MyFunctionProject-myfunction, Invocation ID=00D2F000000Hc8RUAS-4cjx9jRDHsaVPP-qbx-uK--36ad2970, Namespace=, Request ID=4cjx9jRDHsaVPP-qbx-uK-, Payload length=20]
18:20:53.911 (2911368332)|FUNCTION_INVOCATION_RESPONSE|[31]|Function.invoke[Name=MyFunctionProject-myfunction, Invocation ID=00D2F000000Hc8RUAS-4cjx9jRDHsaVPP-qbx-uK--36ad2970, Namespace=, Request ID=4cjx9jRDHsaVPP-qbx-uK-, Response length=1446]
18:20:53.911 (2911428761)|HEAP_ALLOCATE|[31]|Bytes:20
18:20:53.911 (2911456738)|METHOD_EXIT|[6]||functions.Function.invoke(String)
18:20:53.911 (2911464878)|VARIABLE_SCOPE_BEGIN|[6]|invocation|functions.FunctionInvocation|true|false
18:20:53.911 (2911538666)|VARIABLE_ASSIGNMENT|[6]|invocation|{"invocationId":"00D2F000000Hc8RUAS-4 (30 more) ...","response":"{\"done\":true,\"totalS (1426 more) ...","status":"0x536e4e3b"}|0x2e2b5af9
18:20:53.911 (2911551634)|STATEMENT_EXECUTE|[7]
18:20:53.911 (2911570107)|METHOD_ENTRY|[7]||functions.FunctionInvocationImpl.getResponse()
18:20:53.911 (2911605213)|METHOD_EXIT|[7]||functions.FunctionInvocationImpl.getResponse()
18:20:53.911 (2911613656)|VARIABLE_SCOPE_BEGIN|[7]|jsonResponse|String|false|false
18:20:53.911 (2911633134)|VARIABLE_ASSIGNMENT|[7]|jsonResponse|"{\"done\":true,\"totalS (1426 more) ..."
18:20:53.911 (2911640236)|STATEMENT_EXECUTE|[9]
18:20:53.911 (2911644250)|HEAP_ALLOCATE|[9]|Bytes:25
18:20:53.911 (2911664344)|HEAP_ALLOCATE|[9]|Bytes:1471
18:20:53.911 (2911700189)|USER_DEBUG|[9]|DEBUG|Response from myfunction {"done":true,"totalSize":1,"records":[{"type":"Account","fields":{"id":"0012F00000r3LfTQAU","isdeleted":false,"masterrecordid":null,"name":"MyAccount-1624670453815","type":null,"parentid":null,"billingstreet":null,"billingcity":null,"billingstate":null,"billingpostalcode":null,"billingcountry":null,"billinglatitude":null,"billinglongitude":null,"billinggeocodeaccuracy":null,"billingaddress":null,"shippingstreet":null,"shippingcity":null,"shippingstate":null,"shippingpostalcode":null,"shippingcountry":null,"shippinglatitude":null,"shippinglongitude":null,"shippinggeocodeaccuracy":null,"shippingaddress":null,"phone":null,"fax":null,"accountnumber":null,"website":null,"photourl":"/services/images/photo/0012F00000r3LfTQAU","sic":null,"industry":null,"annualrevenue":null,"numberofemployees":null,"ownership":null,"tickersymbol":null,"description":null,"rating":null,"site":null,"ownerid":"0052F000008hjwOQAQ","createddate":"2021-06-26T01:20:54.000+0000","createdbyid":"0052F000008hjwOQAQ","lastmodifieddate":"2021-06-26T01:20:54.000+0000","lastmodifiedbyid":"0052F000008hjwOQAQ","systemmodstamp":"2021-06-26T01:20:54.000+0000","lastactivitydate":null,"lastvieweddate":"2021-06-26T01:20:54.000+0000","lastreferenceddate":"2021-06-26T01:20:54.000+0000","jigsaw":null,"jigsawcompanyid":null,"cleanstatus":"Pending","accountsource":null,"dunsnumber":null,"tradestyle":null,"naicscode":null,"naicsdesc":null,"yearstarted":null,"sicdesc":null}}]}
18:20:53.911 (2911734250)|METHOD_EXIT|[1]|01p2F00000Ap61w|FunctionApex.test()
18:20:53.911 (2911742250)|SYSTEM_MODE_EXIT|false
18:20:53.911 (2911805149)|CUMULATIVE_LIMIT_USAGE
18:20:53.911 (2911805149)|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 0 out of 100
  Number of query rows: 0 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of Publish Immediate DML: 0 out of 150
  Number of DML rows: 0 out of 10000
  Maximum CPU time: 0 out of 10000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10

18:20:53.911 (2911805149)|CUMULATIVE_LIMIT_USAGE_END

18:20:53.911 (2911862726)|CODE_UNIT_FINISHED|execute_anonymous_apex
18:20:53.911 (2911873632)|EXECUTION_FINISHED

See Function Logging to learn how to view logs while the function is running.