function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Janakiraman ChandravadhanJanakiraman Chandravadhan 

Rest API authentication Apex code error

I am facing error in the below code, basically I am trying to perform a Rest API authentication and the code doesn't seem to work. it is throwing a specific error 'Invalid type: OAuth2'. Org B has this code and Org A has the connected App and remote site settings updated.

Any help would be greatly appreciated. Thanks!

below is my code...
public class Samplerest
{
    public string name;

String clientId = 'Client Id' ;
String clientSecret = 'client Secret';
String username= 'username';
String password= 'pwd';

String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='
+clientSecret+'&username='+username+'&password='+password;

Http h = new Http();
    {   
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://playful-wolf-sa1kgu-dev-ed.my.salesforce.com/services/oauth2/token');
HttpResponse res = h.send(req);
        
OAuth2 objAuthenticationInfo =(OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
  }    

  // proceed further only if you get token
if(objAuthenticationInfo.access_token!=null)
{

Http h1 = new Http();
HttpRequest req1 = new HttpRequest();
string EndPt = 'https://playful-wolf-sa1kgu-dev-ed.my.salesforce.com/services/apexrest/AccountRestService?name=' +name;

//request header to send token, setMethod, and set Endpoint
req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
req1.setMethod('GET');
req1.setEndpoint(EndPt);

HttpResponse res1 = h1.send(req1);
system.debug('RESPONSE_BODY'+res1y());
}
}

 
Santosh Reddy MaddhuriSantosh Reddy Maddhuri

Hi Janakiraman,

Try to use

https://login.salesforce.com/services/oauth2/token for Production or Developer Editions

https://test.salesforce.com/services/oauth2/token for Sandboxes


Hope this Helps!

Regards,

Santosh.