Thursday 27 May 2021

Access Token Generation and update existing record from Standard Salesforce REST API

 Hi ,

Here are we are going to learn how to generate access token when you are using connected app for authentication.

When you create a connected app then it provides consumer key (client_id) and consumer secret (client_secret).

Now you should use "username" and "password" of an integration user (any user who access access on your object) .

Now let's start generating access token:

1)Prepare url :

String urlStr = <baseurl>'/services/oauth2/token?grant_type=password&client_id='+<consumerkey>+'&client_secret='+<consumersecret>+'&username='+<username>+'&password='+<passwordwithsecuritytoken>;

Http h = new Http();         

HttpRequest req = new HttpRequest();

req.setEndpoint(urlStr);

req.setMethod('POST');

HttpResponse res = h.send(req);

 Map<String,object>  jsonMap= (Map<String,Object>)JSON.deserializeUntyped(res.getBody());

if(jsonMap.get('access_token')!=null){

String updateURLStr = <baseurl>'/services/data/v52.0/sobjects/Account/'+actId;

req = new HttpRequest();

req.setEndpoint(updateURLStr);

req.setMethod('PATCH');

req.setHeader('Authorization', 'Bearer '+String.valueOf(jsonMap.get('access_token')));

req.setHeader('Content-Type', 'application/json');

req.setBody(JSON.serialize(actObj));

res = h.send(req);


}

Reference:

https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_what_is_rest_api.htm





No comments:

Post a Comment

Best Practices for Building Prompt Templates

 Hi, The following best practices should be considered when building prompt templates: Make sure that your prompt templates are concise and ...