Package: salesforce-functions
sf-functions-pythonPython support forSalesforce Functions.Note: This feature is a Beta Service. Customer may opt to try such Beta Service in its sole discretion. Any use of the Beta Service is subject to the applicable Beta Services Terms provided atAgreements and Terms.Getting Started with Python for FunctionsPrerequisitesInstall commands assume an Apple macOS system with Homebrew available.  If you’re on another OS you’ll have to click through the links to get alternative install instructions.Install Python 3brewinstallpython3The installed Python version must be at least3.10or higher.Check your version of python withpython3 --version.On some machines Python and Pip commands must be run using python3 or pip3, which point to the Homebrew-managed Python interpreter. Using python or pip instead often points at the system installed Python interpreter.Install GitbrewinstallgitThe installed Git version should be at least2.36.0or higher.Check your version of git withgit --version.Install / Update the Salesforce CLIInstall the Salesforce CLIif you haven't already.Update to the latest version of Salesforce CLI that contains
Python functions support:sfdxupdateThe commandsfdx updateupdates both thesfdxandsfcommands.Check your version of the Salesforce CLI withsf --version. The installed version ofsfshould be1.59.0or higher.Create a Salesfoce DX ProjectCreate a DX project in the directory you want your Salesforce Functions project to be located.sfgenerateproject--namePythonFunctionsBetaSome of the following commands run from within the SFDX project directory.Navigate to your SFDX directory:cdPythonFunctionsBetaAdd theFunctionsfeature needed for connecting and deploying Functions in scratch orgs. Edit theconfig/project-scratch-def.jsonfile to include theFunctionsfeature.For example:{"orgName":"SomeOrgName","edition":"Developer","features":["EnableSetPasswordInApi","Functions"],"settings":{"lightningExperienceSettings":{"enableS1DesktopEnabled":true},"mobileSettings":{"enableS1EncryptedStoragePref2":false}}}Note: We recommend using a Dev Hub and scratch org for Salesforce Functions development. SeeConnect and Prepare your Development Environment.Your SFDX project needs to be a git repo to deploy any Salesforce Function because the deployment process
uses git tracked changes to figure out what to deploy.  Run the following commands to setup git:gitinitCommit your changes locally for deployment.It is not a requirement to push your code to GitHub or any other code hosting site but can be useful forsharing and maintaining functions code.Connect Your OrgConfigure your Salesforce org to develop and invoke Salesforce Functions. Develop your functions in scratch
orgs with Dev Hub or in sandbox orgs. Follow the steps onConfigure Your Orgto ensure everything
is setup.Once your Org is configured, log in and set it as the default Dev Hub with the following command:sfloginorg--aliasPythonOrg--set-default-dev-hub--set-defaultPythonOrgis the the default Dev Hub for subsequent commands.Create a scratch org:sfdxforce:org:create\--definitionfileconfig/project-scratch-def.json\--setaliasPythonScratch\--setdefaultusernameNow when you run a Function, it will connect to and use thePythonScratchorg.Connect Your Compute EnvironmentLog in to Salesforce Functions with the same credentials you used to connect your Dev Hub org.sfloginfunctionsCreate the compute environment and associate it with thePythonScratchorg we created while
connecting your org.sfenvcreatecompute\--connected-orgPythonScratch\--aliasPythonComputeFuture functions deployed to thePythonComputeenvironment are linked to
your scratch org.Assign PermissionsThe default Python project requiresreadaccess to theAccountobject in your scratch org. Create
a file namedforce-app/main/default/permissionsets/Functions.permissionset-meta.xmlin your SFDX project and add the following content:<?xml version="1.0" encoding="UTF-8"?><PermissionSetxmlns="http://soap.sforce.com/2006/04/metadata"><description>PermissionsforSalesforceFunctionstoaccessSalesforceorgdata</description><hasActivationRequired>true</hasActivationRequired><label>Functions</label><objectPermissions><allowCreate>false</allowCreate><allowDelete>false</allowDelete><allowEdit>false</allowEdit><allowRead>true</allowRead><modifyAllRecords>false</modifyAllRecords><object>Account</object><viewAllRecords>false</viewAllRecords></objectPermissions></PermissionSet>Upload the permission set to your org.sfdeploymetadata--ignore-conflictsThen assign the permissions to theFunctionsprofile.sfdxforce:user:permset:assign-nFunctionsCreate and Run a Python Function LocallyGenerate the Python FunctionFrom the root directory of your SFDX project, run:sfgeneratefunction\--languagepython\--function-namehellopythonNavigate to thehellopythonfolder.cdfunctions/hellopythonCreate the PythonVirtual Environment& Install DependenciesCreate a "Virtual Environment" (venv) before installing the dependencies required to run the Python function locally.
Install using packages without affecting your system Python installation by setting up your virtual environment.Create the virtual environment.python3-mvenv.venvActivate the virtual environment.On amacOS / Linux system:source.venv/bin/activateOn aMicrosoft Windows system:.\.venv\Scripts\activateSee thePython documentationfor help with setting up a virtual environment.Finally, install the dependencies into the virtual environment.pip3install--upgrade-rrequirements.txtUsing a virtual environment ensures your function has all required dependencies before you run it.Note: Starting the Function locally without setting up your virtual environment results in an error.Run the Python Function LocallyStart the function running locally.sfrunfunctionstartMessages logged by the running function will appear onhttp://localhost:8080.Invoke the Running Python FunctionAfter starting the function, open a new command line terminal and navigate to thehellopythondirectory.Invoke the function by sending it a payload.sfrunfunction--function-urlhttp://localhost:8080--payload'{}'Deploy the Python FunctionChange to the root directory of your SFDX project before committing changes and running your function.cd../../Commit your changes to GitAll code changes made to a function need to be staged and committed before you can deploy.Commit all changes to your project.gitadd.
gitcommit-m"Trying out python functions"Deploy your functions project.sfdeployfunctions--connected-orgPythonScratchThis deployment process may take several minutes.Note: If you receive aRequest failed with status code 404error message, check the earliersf env create computestep was performed.Invoke the Function from ApexUse Apex to invoke the function deployed to our scratch org. Generate an Apex class with:sfdxforce:apex:class:create\--classnameApexTrigger\--outputdirforce-app/main/default/classesHave your apex code lookup the reference to our function using thefunctions.Function.getmethod, invoke the function with an empty json payload, and
print the response.Openforce-app/main/default/classes/ApexTrigger.clsand replace it's contents with:publicwithsharingclassApexTrigger{publicstaticvoidrunFunction(){System.debug('Runninghellopython');functions.Functionfn=functions.Function.get('PythonFunctionsBeta.hellopython');functions.FunctionInvocationinvocation=fn.invoke('{}');System.debug('Response:'+invocation.getResponse());}}Upload this Apex class to your scratch org.sfdxforce:source:push--targetusernamePythonScratchOpen a developer console.sfdxforce:org:open-p/_ui/common/apex/debug/ApexCSIPageExecute the function from the developer console.On amacOS / Linux system:echo"ApexTrigger.runFunction();"|sfdxforce:apex:execute-f/dev/stdinOn aMicrosoft Windows system:echo"FunctionApex.test();"|sfdxforce:apex:executeThe developer console shows a log entry in the bottom panel after the function executes, which you can double-click to open.
Toggle the Debug Only filter to reduce the log messages to just the ones from theApexTriggerfunction.You should see a view like the one below:NOTE: You may encounter the following errorSystem.CalloutException: Error during Salesforce Functions Sync Invocation. Ensure that 
function 'PythonFunctionsBeta.hellopython' is deployed and its status is 
available ('OK', 'up'). If issue persists, contact Salesforce Support.If you see this then there may not be a problem, the function just might not be available yet in the compute
environment. Wait several minutes and then try the command above again.