0

I have a Python program that performs a REST API call:

def get_token(self):

        try:
            target_url = 'http://auth-{0}-{1}.{2}{3}/token'.format(
                self.country,
                self.environment,
                self.domain_pref,
                self.domain
                )
            
            payload = {
                'username': keys[self.project][self.environment]['username'],
                'password': keys[self.project][self.environment]['password'],
                'client_id': keys['client_id'],
                'client_secret': keys['client_secret'],
                'grant_type' : 'password'
                    }

            headers = {'Cache-Control': 'no-cache'}
            response = requests.post(target_url, data=payload,headers=headers)
            token = '{0} {1}'.format('Bearer',response.json()['access_token'])
            return token
        except Exception as e:
            logging.error(response.status_code)
            logging.error(response.content)
            raise e

I translated the Python program to Apex. Running the Apex code returns 400:


        // oAuth2 client credentials
        String username = 'myemail@gmail.com';
        String password = 'password';
        String clientId = 'myclientid';
        String clientSecret = 'myclientsecret';
        String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;

        // AP token endpoint setup
        String tokenAPEndpoint = 'http://auth-{0}-live.mydomain.com/token';
        String formattedTokenEndpoint;
        String token;

            String[] formatArgumentsToken = new String[]{'mx'};
            formattedTokenEndpoint = String.format(tokenAPEndpoint, formatArgumentsToken);
            System.debug('URL ' + formattedTokenEndpoint);

            HttpRequest requestToken = new HttpRequest();
            requestToken.setEndpoint(formattedTokenEndpoint);
            requestToken.setHeader('Content-Type','application/json');
            requestToken.setBody(reqbody);
            requestToken.setMethod('POST');

            system.debug('grant_type set to:' + requestToken.getHeader('grant_type'));
            system.debug('client_secret set to:' + requestToken.getHeader('client_secret'));
            system.debug('username set to:' + requestToken.getHeader('username'));
            
            Http httpGetToken = new Http();
            HttpResponse responseToken = httpGetToken.send(requestToken);
            
            system.debug('Response' + responseToken);
            system.debug('notification body' + responseToken.getBody());

Any help as to how this supposed to be done would be greatly appreciated!

3

The big difference between the one that works (Py) and the one that doesn't (Salesforce) is the request body.

In the Python example, you have constructed a key-value map that correctly reads like JSON, whereas in the Salesforce example it looks more like you are writing URL parameters in the request body.

You will want create a Map<String,String> with your body parameters and serialise it to JSON, then use that JSON string as the request body.

An example here on how to serialise a map to JSON: Serialize a Map into a specific JSON object

1
  • thank you Diego, the answer I was looking for. I just needed to specify the body as JSON object in APEX. – Adnan Zahry Nov 24 '20 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.