[SalesForce] Using simple-salesforce with oAuth

I have a need to query salesforce data through a django app. I am currently using simple-salesforce to do this on our QA salesforce using a username, password and a security token. Now that I am moving on to the production environment, I need to use oAuth. I have a Client ID and a Client Secret from the connected app.

I have tried these variations with failed authentication results:

session_id, instance = SalesforceLogin(username=username, 
password=password, security_token=token, organizationId=org_id)

sf = Salesforce(instance=instance, session_id=session_id)

and

sf = Salesforce(instance_url=instance_url, username=username, password=password, security_token=token)

I do see that simple-salesforce supports JWT Bearer flow but I do not have a private key.

Best Answer

Instead of going for Simple_Salesforce package try doing it through Request package.Here is piece of code i did in my project.

I am using a config.ini files PARAMS values.

        [access]
        l_grant_type = password            
        l_client_id = provide your cliend-Id
        l_client_secret = Provide your Client Secret
        l_username = Provide UserName
        l_password = provide Password alongwith security token
        [oauth]
        #this is for sandbox Org
        url = https://test.salesforce.com/services/oauth2/token
        #This is for Production Org
        url = https://login.salesforce.com/services/oauth2/token  

Code to get the access token:

        import requests

        # defining a params dict for the parameters to be sent to the API
        PARAMS = {'grant_type': self.config['access']['l_grant_type'],
                  'client_id': self.config['access']['l_client_id'],
                  'client_secret': self.config['access']['l_client_secret'],
                  'username': self.config['access']['l_username'],
                  'password': self.config['access']['l_password']}

        # sending get request and saving the response as response object
        authorization_response = requests.post(url=self.config['oauth']['url'], data=PARAMS)
        print('authorization response: {}'.format(authorization_response))

authorization_response.json() will contain the access token, which can be utilise throughout the session as OAuth token for communicating with salesforce.

Related Topic