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:

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

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

Tip

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

1public with sharing class FunctionApex {
2    public static void test() {
3        System.debug('Invoking myfunction');
4
5        functions.Function myFunction = functions.Function.get('MyFunctionProject.myfunction');
6        functions.FunctionInvocation invocation = myFunction.invoke('{"name":"MyAccount"}');
7        String jsonResponse = invocation.getResponse();
8
9        System.debug('Response from myfunction ' + jsonResponse);
10    }
11}

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:

1sf project deploy start --target-org MyOrgAlias

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

Tip

Debug Apex Code Deploy 

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

1PROJECT PATH                   ERRORS
2
3─────────────────────────────────────────────── ──────────────────────────────────────────────
4
5force-app/main/default/classes/FunctionApex.cls Type is not visible: functions.Function (5:9)
6
7force-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:

1<?xml version="1.0" encoding="UTF-8" ?>
2<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
3    <apiVersion>53.0</apiVersion>
4    <status>Active</status>
5</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.

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

Now, invoke your Apex code to execute your function:

Linux/OSX

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

Windows

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

The output looks something like this:

1Compiled successfully.
2Executed successfully.
3
452.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;NBA,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WAVE,INFO;WORKFLOW,INFO
5Execute Anonymous: FunctionApex.test();
6
7...
8
918:20:51.102 (286350229)|METHOD_ENTRY|[6]||functions.Function.invoke(String)
1018: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]
1118: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]
1218:20:53.911 (2911428761)|HEAP_ALLOCATE|[31]|Bytes:20
1318:20:53.911 (2911456738)|METHOD_EXIT|[6]||functions.Function.invoke(String)
1418:20:53.911 (2911464878)|VARIABLE_SCOPE_BEGIN|[6]|invocation|functions.FunctionInvocation|true|false
1518:20:53.911 (2911538666)|VARIABLE_ASSIGNMENT|[6]|invocation|{"invocationId":"00D2F000000Hc8RUAS-4 (30 more) ...","response":"{\"done\":true,\"totalS (1426 more) ...","status":"0x536e4e3b"}|0x2e2b5af9
1618:20:53.911 (2911551634)|STATEMENT_EXECUTE|[7]
1718:20:53.911 (2911570107)|METHOD_ENTRY|[7]||functions.FunctionInvocationImpl.getResponse()
1818:20:53.911 (2911605213)|METHOD_EXIT|[7]||functions.FunctionInvocationImpl.getResponse()
1918:20:53.911 (2911613656)|VARIABLE_SCOPE_BEGIN|[7]|jsonResponse|String|false|false
2018:20:53.911 (2911633134)|VARIABLE_ASSIGNMENT|[7]|jsonResponse|"{\"done\":true,\"totalS (1426 more) ..."
2118:20:53.911 (2911640236)|STATEMENT_EXECUTE|[9]
2218:20:53.911 (2911644250)|HEAP_ALLOCATE|[9]|Bytes:25
2318:20:53.911 (2911664344)|HEAP_ALLOCATE|[9]|Bytes:1471
2418: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}}]}
2518:20:53.911 (2911734250)|METHOD_EXIT|[1]|01p2F00000Ap61w|FunctionApex.test()
2618:20:53.911 (2911742250)|SYSTEM_MODE_EXIT|false
2718:20:53.911 (2911805149)|CUMULATIVE_LIMIT_USAGE
2818:20:53.911 (2911805149)|LIMIT_USAGE_FOR_NS|(default)|
29  Number of SOQL queries: 0 out of 100
30  Number of query rows: 0 out of 50000
31  Number of SOSL queries: 0 out of 20
32  Number of DML statements: 0 out of 150
33  Number of Publish Immediate DML: 0 out of 150
34  Number of DML rows: 0 out of 10000
35  Maximum CPU time: 0 out of 10000
36  Maximum heap size: 0 out of 6000000
37  Number of callouts: 0 out of 100
38  Number of Email Invocations: 0 out of 10
39  Number of future calls: 0 out of 50
40  Number of queueable jobs added to the queue: 0 out of 50
41  Number of Mobile Apex push calls: 0 out of 10
42
4318:20:53.911 (2911805149)|CUMULATIVE_LIMIT_USAGE_END
44
4518:20:53.911 (2911862726)|CODE_UNIT_FINISHED|execute_anonymous_apex
4618:20:53.911 (2911873632)|EXECUTION_FINISHED

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

Product Retirement Announcement

Salesforce Functions is no longer available for purchase or renewal. To preserve the capabilities that Salesforce Functions provided to your org, deploy an alternative solution before your existing order term ends. See Salesforce Functions Retirement for more information on migrating your functions. Contact your Salesforce Account Executive for more information on Heroku.