• farukh sk hd
  • NEWBIE
  • 40 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 116
    Replies
Can somebody help me over here,I am getting error and I am not able to create a record using rest api from one salesforce org to other.

Here is my code,

public void getConList()
{

list<account> accList1=new list<account>();
String accToken;
string responseBody;
string endPoint='https://ap5.salesforce.com/services/apexrest/getAccountOnExternalId';
restApiClassSalesforceorg1 obj=new restApiClassSalesforceorg1();
accToken=obj.getRequestToken();
system.debug('access token'+ accToken);
if(accToken!='')
{
String accName1='Test from org 1 to org 2';
string Jsonstring='{"Name":"Acc from org 1"}';
Http h1=new Http();
HttpRequest req1=new HttpRequest();
req1.setHeader('Authorization','Bearer '+accToken);
req1.setHeader('Content-Type','application/json');
//req1.setHeader('accept','application/json');
req1.setMethod('POST');
req1.setBody(Jsonstring);
req1.setEndpoint(endPoint);
HttpResponse hresp1=h1.send(req1);
system.debug('hresp1'+ hresp1);
//listWrap=(list<resultWrapper>) JSON.deserialize(hresp1.getBody(),list<resultWrapper>.class);

}

// return listWrap;

}





@RestResource(urlMapping='/getAccountOnExternalId/*')
   global with sharing class getAccount {
     @HttpPost
      global Static string fetchAccount(string name1){
      Account obj=new account();
      obj.name=name1;
      Insert obj;
        
        return 'Success';
      }
   }
Can somebody help me here I am getting the error while getting data based on id which I am passing, I am able to generate session id as well.

Salesforce to Salesforce Rest Api Integration.

My code is,

public class restApiClassSalesforceorg1{


private string cKey='XXXXXX';
private string cSecret='XXXXXX';
private string uName='XXXXXX';
private string passwd='XXXXXX';

// Above information is hided


public class responseWrapper{

public string id;
public string access_token;
public string instance_url;

}

public string getRequestToken()
{
string reqBody='grant_type=password&client_id='+cKey+'&client_secret='+cSecret+'&username='+uName+'&password='+passwd;                                      

Http h=new Http();
HttpRequest req=new HttpRequest();
req.setBody(reqBody);
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');

HttpResponse hresp=h.send(req);
responseWrapper wResp=(responseWrapper)JSON.deserialize(hresp.getBody(),responseWrapper.class);
system.debug('Instance url'+wResp.instance_url);
system.debug('session id'+wResp.access_token);
return wResp.access_token;


}

public static list<Account> getConList()
{
list<account> accList1=new list<account>();
String accToken;
string ExternalId='SomeIDfromOtherOrg';
string responseBody;
string endPoint='https://ap5.salesforce.com/services/apexrest/v1/getAccountOnExternalId/' + ExternalId;
restApiClassSalesforceorg1 obj=new restApiClassSalesforceorg1();
accToken=obj.getRequestToken();
system.debug('access token'+ accToken);
if(accToken!='')
{
Http h1=new Http();
HttpRequest req1=new HttpRequest();
req1.setHeader('Authorization','Bearer'+accToken);
req1.setHeader('Content-Type','application/json');
//req1.setHeader('Accept','application/json');
req1.setMethod('GET');
req1.setEndpoint(endPoint);
HttpResponse hresp1=h1.send(req1);
responseBody=hresp1.getBody();
JSONParser parser=JSON.createParser(responseBody);
 while (parser.nextToken() != null) {
 Account obj1=new Account();
 if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Name')) {
 
 string accName=parser.getText();
 obj1.name=accName;
 
 }
accList1.add(obj1);
}
}
return accList1;

}



}

Code from other org,

@RestResource(urlMapping='/v1/getAccountOnExternalId/*')
   global with sharing class getAccount {
     @Httpget
      global static list<Account> fetchAccount(){
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        string accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        list<Account> lstAcc=[Select id , name,ExternalIdForAccount__c from Account where Id=:accId ];
        
        return lstAcc;
      }
   }


 
Can somebody help me over here,I am getting error and I am not able to create a record using rest api from one salesforce org to other.

Here is my code,

public void getConList()
{

list<account> accList1=new list<account>();
String accToken;
string responseBody;
string endPoint='https://ap5.salesforce.com/services/apexrest/getAccountOnExternalId';
restApiClassSalesforceorg1 obj=new restApiClassSalesforceorg1();
accToken=obj.getRequestToken();
system.debug('access token'+ accToken);
if(accToken!='')
{
String accName1='Test from org 1 to org 2';
string Jsonstring='{"Name":"Acc from org 1"}';
Http h1=new Http();
HttpRequest req1=new HttpRequest();
req1.setHeader('Authorization','Bearer '+accToken);
req1.setHeader('Content-Type','application/json');
//req1.setHeader('accept','application/json');
req1.setMethod('POST');
req1.setBody(Jsonstring);
req1.setEndpoint(endPoint);
HttpResponse hresp1=h1.send(req1);
system.debug('hresp1'+ hresp1);
//listWrap=(list<resultWrapper>) JSON.deserialize(hresp1.getBody(),list<resultWrapper>.class);

}

// return listWrap;

}





@RestResource(urlMapping='/getAccountOnExternalId/*')
   global with sharing class getAccount {
     @HttpPost
      global Static string fetchAccount(string name1){
      Account obj=new account();
      obj.name=name1;
      Insert obj;
        
        return 'Success';
      }
   }
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
List<ID>ownerids=new List<ID>();

List<String> sendTo = new List<String>();
List<User>users=new List<User>();

for (case mycase : Trigger.new) {

    case oldcon = Trigger.oldMap.get(mycase.Id)
        
    
 if (mycase.ownerid != oldcon.ownerid ) {

     ownerids.add(oldcon.ownerid) ; 

     }
    }

   users=[select name,id,email from user where id in:ownerids];
    for(User u:users){

      sendTo.add(u.Email); 

    }

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSenderDisplayName('Email alert');
mail.setSubject('Owner change');
String body = 'Dear User Owner changed';
mail.setToAddresses(sendTo);
mail.setPlainTextBody(body);
mails.add(mail);
Messaging.sendEmail(mails);
0down votefavorite
I need to make integration between Org1 and Org2. We created a callout POST. When we create an object in Org1, we also create an object in Org2. POST work. All is Ok. Now I need also delete an object in Org2, if External Id in this obj == Id in obj from Org1.
Something like that:
If(org2Object.ExternalId == org1Object.Id){
   Delete org2Object;
}

I try to delete a record from another org, but I don't know, how to write it right. My Delete callout:
private static Position__c pos = [SELECT Id, Name, Location__c, Job_Description__c, Salary_Range__c, Skills_Required__c, Education__c,
                       Hiring_Manager__r.Name, Email__c, Phone__c, Status__c
                       FROM Position__c WHERE Name = 'Title22'];

public static String getRequestBody(){
    Settings__c settings = [SELECT ConsumerKey__c, ClientSecret__c, Username__c, Password__c, SecurityToken__c
                            FROM Settings__c
                            WHERE Name = 'OurSettings'];  
    String consumerKey = settings.ConsumerKey__c;
    String consumerSecret = settings.ClientSecret__c;
    String username = settings.Username__c;
    String password = settings.Password__c + settings.SecurityToken__c;
    String request = 'grant_type=password&client_id=' + consumerKey +'&client_secret=' + consumerSecret +
                     '&username=' + username + '&password='+password;
    return request;
}


public static void deleteCalloutResponseContents(Id ourId){
    Http ourHttp = new Http();
    HttpRequest request = httpRequest('DELETE');
    HttpResponse response = ourHttp.send(request);
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(response.getbody(), OAuth2.class);

    if(objAuthenticationInfo.ACCESS_TOKEN != null){
        pos.Id = ourId;

        HttpRequest finalRequest = new HttpRequest();
        String jsonstr='{"Position_ID__c":"'+ ourId +'"}';

        finalRequest.setHeader('Authorization','Bearer '+ objAuthenticationInfo.ACCESS_TOKEN);
        finalRequest.setHeader('Content-Type','application/json');
        finalRequest.setHeader('accept','application/json');
        finalRequest.setBody(jsonstr);
        finalRequest.setMethod('DELETE');

        request.setEndpoint(System.Label.Job_Advertisement_URL + '/services/data/v43.0/sobjects/Job_Advertisement__c/ourId');
        response = ourHttp.send(finalRequest);
        System.debug('RESPONSE BODY: ' + response.getBody());
    }        
}

public class OAuth2{
        public String ACCESS_TOKEN{get;set;}    
    }

How can I fix it?
hi guys,

i will try to create and update a record in SFDC via API. I have acheived to create a Record .But I can't able to update  the Record via API . 

Here is my sample code :
        public void UpdatedRecordforAccount()
        {
            //0017F00000b9EnPQAU
            HttpClient client = new HttpClient();
            string requestMessage = "{\"Name\":\"Express Logistics and Transport Sample\"}";


            HttpContent content = new StringContent(requestMessage, Encoding.UTF8, "application/json");            
            string uri = InstanceUrl + API_ENDPOINT + "sobjects/Account/0017F00000b9EnPQAU" + "?_HttpMethod=PATCH";

            //create request message associated with POST verb
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

            //add token to header
            request.Headers.Add("Authorization", "Bearer " + AuthToken);

            //return xml to the caller
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Content = content;
            var response = client.SendAsync(request).Result;
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            Console.ReadLine();
        }

I have already tried these two method (http put,post) and _Patch concept. If any have a solution .please share to me 
Hi Everyone,

Could you explain what is "Connected App" in salesforce and what are its usage.
If you provide example for this means,It would be great..

Thanks,
​Vignesh.B
I am new for Integration , Please help me  How to establish a connection One Org to another Org by using Rest API Oauth 2 and Consumer Id and consumer Secret .

Could you please give me sample code ......       

Thanks in advance
  • January 04, 2017
  • Like
  • 0
Hi friends
This is an urgent requirement, kindly help.
I have two different salesforce accounts  and I am trying to delete records based on criteria using rest api annotation @HttpDelete

The code in destination is:
@HTTPDelete 
 webservice static string DeleteAccounts()  
 {
    Account a=[select Id from account where Name LIKE :'%TVS Electronics%'];
    return a.ID;
 }
}
The code in source is:

          Http h = new Http();
         
          HttpRequest req = new HttpRequest();
       
          req.setMethod('DELETE');
       
          req.setHeader('Authorization','Bearer '+Helper.GetAccessToken().access_token);
       
          req.setHeader('Content-Type','application/json; charset=UTF-8');
         
          //call the rest resource URL and this url needs to be registered in remote settings
          req.setEndpoint('https://ap2.salesforce.com/services/apexrest/AccountRest');  
           
          HttpResponse res = h.send(req); // JSON string is generated at this point
 system.debug('---res.getBody()--'+res.getBody());

In res.getBody() , I am getting the ID of the record which was passed from source
Now how do I pass this ID back to source indicating that this record is to be deleted.

I hope I am clear

Thanks
pooja
 
Hello All,
   i have gone through list and map, would any one share same example using LIST and MAP using 2 object. i am still confused when do i use list and when do i use map? please give me one common example , how MAP reduces code over LIST ?

Thanks,
 
I keep getting an error message when trying to save this code. 

Error: Compile Error: Illegal modifier on local variable at line 7 column 19

Code:
public class PackageLicenseDelete
{
    @InvocableMethod
    public static void licenseDelete()
    {
        @InvocableVariable(required=true)
		public ID UserId;
		@InvocableVariable(required=true)
		public String PackageID;
		
		//Use the UserId and PackageID to delete record from UserPackageLicense
   }
}

I need to pass two variables to the apex plugin so I can delete UserPackageLicense records. 

Thanks for any help,
Matt
 
Dear Salesforce Specialists,

You guys are doing awesome Job in providing the best knowledge for almost all the questions posted on forums,

I do have a request :

I am very new to the Webservices & Integration

1) How to learn Web services - Integration & Where to start ( Step - By Step Resources : Documentation , PDF's , VIdeo;s , Usefull Blogs ? )

2) Salesforce Rest & Soap - Where to start ( Step - By Step Resources : Documentation , PDF's , VIdeo;s , Usefull Blogs ? )

3) Any Real-time impmemention's ( With : Oracle, SAP, SQL,JAVA) for references ?

4) Does big Clients use Third-Party tools for automating Integration ( Ex: Jitterbit , Boomi , Informatica ) , If so which one is best tool to use ?

One of our client project is about to start and I am involved in that and I am in real confusion from where to start learning and reach the stage of implementing?

I hope some of you guys helps me ,

Thanks,
Janardhan
 
Hello Experts,
I have registered my app. Could you please help in letting me know how to get:
1. client_id,
2. client secret, and
3. security token

I am trying to implement Oauth pragramatically so that I can use REST API.

Could you please help.

Thanks,
Rakesh
I have a requirement to integrate between two salesforce applications(orgs). The integration I need to used is rest api integration.
Please help me by giving me a head start how should I begin.
To be more specific my requirement is to exectue a search functionality in one salesforce org which fetchs and displays data present another salesforce org using rest api integration.


  • August 07, 2014
  • Like
  • 0
Hi,

I want to use REST API callouts from Salesforce to an external website's REST based API to pull and push the data into the salesforce.

Could anyone please provide me the sample code if anybody has done that  before?

regards,
Mani

Hi,

 

We are looking to  create a record (Asset) as an appliance in an external system from Salesforce.

 

This would get triggered when a button is clicked upon on the Asset object

 

Can you please guide to some code samples that use REST APIs to connect to external systems and insert records in it and in return fetch a value which is created in the external system.

 

 

Requests:


Action |HTTP Method| URL|
Create | POST | http://xyz.com/sfapi/appliance/
Read GET http://rxyz.com/sfapi/appliance/:id
Update PUT http://xyz.com/sfapi/appliance/:id
Delete DELETE http://rmc.com/sfapi/appliance/:id

 

 

i want to create a method (via PUT) of the Apex REST web service  to receive a list of string and also the code to invoke it from java.

  • December 06, 2011
  • Like
  • 0

Hello. I want to know how can i create a Map<String, CustomObject> where the key will not be the Id of the custom field but the Name field and without using a list and going through each record and puting in the map a pair.

If I use Map<String, CustomObject__c> myMap = new Map<String, CustomObject__c>([Select z.Name, z.Id From CustomObject__c z]); i have a map where the key is my CustomObject.Id and I want it to be CustomObject.Name.

Hello, I spend a lot of time in search how to use the rest api, but only i find information to use the rest api with oAuth, but in dont want to use oauth, i want to type the username and password in the code and this is all, i want to make an app where the client dont see any rest api comunication, I mean execute the apex code in background.

 

I find a code in http://208.69.57.141/index.php/2011/05/using-the-salesforce-rest-api-with-javascript-and-jquery-in-visualforce-pages-using-apex/#comments

 

 

But show me a error [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

 

Thanks

  • September 08, 2011
  • Like
  • 0

Hi everyone,

 

    I am a newbie to FDC (so please correct me if I am wrong anywhere) . I have gone thorugh Apex REST API and found that we can create our custom web services in Apex and expose them as REST services using Apex REST. But in most of the references it is given that we can use any programming language of our choice ( i.e. from outside FDC) to invoke this custom WS via REST API. But I want to invoke the same using Apex code (i.e., from inside FDC) via REST API.

 

Any help is highly appreciated

  • August 25, 2011
  • Like
  • 0