+ Start a Discussion
Deepu BDeepu B 

How to pass Values dynamically in REST API URL

I created a resource to insert an Account record with fields- Name and Description in SF1(say), and i want to send the values from another instance SF2(say) using REST API from URL parameters.

I created one VF page with fields Name and Description. when i entered Name and Description fields respectively they should go to contoller dynamically and create the record in resource instance.

My question is how to pass the values from VF page to Controller(into URL parameters.)?
Best Answer chosen by Deepu B
Sunil02KumarSunil02Kumar
Hi Deepu,

Create apex rest serevice in SF instance 1 to create account.
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
  
  @HttpPost
    global static String doPost(String name,
        String phone, String website) {
        Account account = new Account();
        account.Name = name;
        account.phone = phone;
        account.website = website;
        insert account;
        return account.Id;
    }
}
If you creating account record from one developer org to another developer org, then i will suggest to create domain in your org and then specify the endPoint URL as 'https://'+domainname+'/services/apexrest/Account' instead of 'https://login.salesforce.com/services/apexrest/Account'

here /services/apexrest/Account refers to your apex rest service created above:

In SF instance 2, you can write code for Auth 2.0 autrhentication to get access token of SF instance 1. Now I assume you have access token for SF instance 1.
Now in SF instance 2, create a VF page and class,

VF Page:
<apex:page controller="Apex_Rest_DemoController">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Create Account in SF1 instance" action="{!CreateAccount}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aname" value="Name"></apex:outputLabel>
                <apex:inputText value="{!accName}" id="aname"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aphone" value="Phone"></apex:outputLabel>
                <apex:inputText value="{!accPhone}" id="aphone"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aw" value="Website"></apex:outputLabel>
                <apex:inputText value="{!accWebsite}" id="aw"/>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
    <apex:pageBlock title="Response">
        <apex:pageBlockSection >
            <apex:outputText value="{!Response}"></apex:outputText>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Class:
public class Apex_Rest_DemoController {
	
	public String response{get;set;}
    public String accName{get;set;}
    public String accPhone{get;set;}
    public String accWebsite{get;set;}
	
    public PageReference CreateAccount() {
        //find access token using Auth 2.0 
        String Access_Token='00D90000000IExn!AQgAQGAmok5mK0LmFvr9AYm7JA0JxUOMPUxcVcMelv9LsH6Fmqo4R8rLwjNFaeHbpYowC.dQTKwVBMnWxY_knl3T2UtaXC';
        Httprequest req=new httprequest();
		String domainName='XXXXX-dev-ed.my.salesforce.com';
        String endPointURL='https://'+domainName+'/services/data/v27.0/sobjects/Account';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
        req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
        req.setmethod('POST');
        req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        response=res.getbody();
        System.debug('****************res.getStatusCode();'+res.getStatusCode());
        System.debug('****************res.getbody();'+res.getbody());
        return null;
    }
}
Now when you click on "Create Account in SF1 instance" button, a new account will be created with values specified in your VF Page.

Hope this will help you.
[If it solves your problem, please mark it as solution]

Thanks,
Sunil Kumar

All Answers

Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Deepu,

Here is the example to pass parameters through from vf page to controller.

VF Page:--
<apex:page standardController="Contact" extensions="PassValueExampleController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:outputField value="{!contact.name}"/>
                <apex:commandLink value="Submit" action="{!onSubmit}">
                    //Apex param tag will carry value to controller
                    <apex:param value="{!contact.Id}" name="ContactId"/>
                </apex:commandLink>
            </apex:pageBlockSection>   
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Controller:--
public class PassValueExampleController {
    public PassValueExampleController(ApexPages.StandardController controller) {
    }
    public Pagereference onSubmit(){
       //Here you will get value from current page by using param name.
       String ContactRecId =Apexpages.currentPage().getParameters().get('ContactId');
       system.debug('---ContactRecId -----'+ContactRecId);
       return null;
    }
}

 
Sunil02KumarSunil02Kumar
Hi Deepu,

Create apex rest serevice in SF instance 1 to create account.
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
  
  @HttpPost
    global static String doPost(String name,
        String phone, String website) {
        Account account = new Account();
        account.Name = name;
        account.phone = phone;
        account.website = website;
        insert account;
        return account.Id;
    }
}
If you creating account record from one developer org to another developer org, then i will suggest to create domain in your org and then specify the endPoint URL as 'https://'+domainname+'/services/apexrest/Account' instead of 'https://login.salesforce.com/services/apexrest/Account'

here /services/apexrest/Account refers to your apex rest service created above:

In SF instance 2, you can write code for Auth 2.0 autrhentication to get access token of SF instance 1. Now I assume you have access token for SF instance 1.
Now in SF instance 2, create a VF page and class,

VF Page:
<apex:page controller="Apex_Rest_DemoController">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Create Account in SF1 instance" action="{!CreateAccount}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aname" value="Name"></apex:outputLabel>
                <apex:inputText value="{!accName}" id="aname"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aphone" value="Phone"></apex:outputLabel>
                <apex:inputText value="{!accPhone}" id="aphone"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >
                <apex:outputLabel for="aw" value="Website"></apex:outputLabel>
                <apex:inputText value="{!accWebsite}" id="aw"/>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
    <apex:pageBlock title="Response">
        <apex:pageBlockSection >
            <apex:outputText value="{!Response}"></apex:outputText>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Class:
public class Apex_Rest_DemoController {
	
	public String response{get;set;}
    public String accName{get;set;}
    public String accPhone{get;set;}
    public String accWebsite{get;set;}
	
    public PageReference CreateAccount() {
        //find access token using Auth 2.0 
        String Access_Token='00D90000000IExn!AQgAQGAmok5mK0LmFvr9AYm7JA0JxUOMPUxcVcMelv9LsH6Fmqo4R8rLwjNFaeHbpYowC.dQTKwVBMnWxY_knl3T2UtaXC';
        Httprequest req=new httprequest();
		String domainName='XXXXX-dev-ed.my.salesforce.com';
        String endPointURL='https://'+domainName+'/services/data/v27.0/sobjects/Account';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
        req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
        req.setmethod('POST');
        req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        response=res.getbody();
        System.debug('****************res.getStatusCode();'+res.getStatusCode());
        System.debug('****************res.getbody();'+res.getbody());
        return null;
    }
}
Now when you click on "Create Account in SF1 instance" button, a new account will be created with values specified in your VF Page.

Hope this will help you.
[If it solves your problem, please mark it as solution]

Thanks,
Sunil Kumar
This was selected as the best answer
Deepu BDeepu B
Hi Kumar_sunil,

I followed your code, i replaced access token with my consumer key andtried it. It throwing this below error, i also find this same error in other example also, why this error will come what is the reason for it and solution for it 

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]


Thank you.
Sunil02KumarSunil02Kumar
Hi Deepu,

Consumer key is different then Access token. Refer below URL to understand how to generate Access_Token.

https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com
Once you get access_token, then you can use it in HTTP Request.

Or

you can use sessionid of user logged in to SF instance 2  in HTTP Request. Use
string sessionid='XXXXXXXXXXXXXXXXXXXX';//sessionId of user logged into SF instance 2
req.setHeader('Authorization', 'Bearer ' +sessionid);
instead of 
 req.setHeader('Authorization','Authorization: Bearer '+Access_Token);

Hope this will help you.
[If it solves your problem, please mark it as solution]

Thanks,
Sunil Kumar
 
Deepu BDeepu B
I am using 2 step authentication(Username/passwrod) format and using GET method to insert record, any way i will also try out this way.

Tell me this one Sunil, 
Do we have session id for REST API?, i though it had only for SOAP API.!   
Sunil02KumarSunil02Kumar
Hi Deepu,

SessionId or Access_token is required by application to validate the request send by user or different application( either you are using SOAP API or REST API). If you are going to use sessionId, then you need to specify or store  the username and password for user.
In SOAP API, we store these information and before sending any request, we first send request to get the sessionid of the user from other application. Then in next request we specify sessionId in order to perform any operation.

In REST API, we won't store user credential. User authorize themselves to access other application resources on their behalf without revealing their passwords or other credentials to calling applications. Alternatively, applications can directly authenticate to access the same resources without the presence of an end user. OAuth allows a client application restricted access to your data at a resource server via tokens issued by an authorization server in response to your authorization.

Thanks,
Sunil Kumar
Deepu BDeepu B
Hi Sunil,

Thank you for your answers, and easily understandable, but i  am missing a little clarity on this, could you please answer me in privately, in abatini27@gmail.com(Ping me as API) i will catch you. 

Thanks
Deepu.
Kathir DevanKathir Devan
Hi Sunil,
Very nice article.I have some doubt  what is this String Access_Token='00D90000000IExn!AQgAQGAmok5mK0LmFvr9AYm7JA0JxUOMPUxcVcMelv9LsH6Fmqo4R8rLwjNFaeHbpYowC.dQTKwVBMnWxY_knl3T2UtaXC';

I mentioned bold above code Where do i get.. and i mentioned underline it's consumer key am i rite and last one is security token.but am getting invalid session.kindly help me this issue.Thanks in advance.

Thanks,
Kathir

 
Sunil02KumarSunil02Kumar
Hi Kathir,

Access_token is different from consumer key and secret key. Follow steps mentioned in below URL on how to get Access token using AUTH 2.0

https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com

Thanks,
Sunil Kumar
Kathir DevanKathir Devan
Thanku for respose Sunil.I am getting same error this:[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]. am not able to resolve this issue.

Thanks,
Kathir
Sunil02KumarSunil02Kumar
Hi Kathir,

I assume you are using sessionId for authentication. Login to other instance where you want to create account and get sessiondId by opening developer console and using below code:

system.debug('sessionid***'+userinfo.getsessionid());
copy the sessionid and then use it in HTTPRequest.

If you are using Auth 2.0 , then generate access token as specified in url provide above.

Thanks,
Sunil Kumar
Kathir DevanKathir Devan
Hi Sunil,

Please find my screenshot do i need to change anything..and code also .I eagar to resolve this issue..Thanks in advance
public class Apex_Rest_DemoController {
    
    public String response{get;set;}
    public String accName{get;set;}
    public String accPhone{get;set;}
    public String accWebsite{get;set;}
    
    public PageReference CreateAccount() {
        //find access token using Auth 2.0 
                             
                            

        String Access_Token='3MVG9Y6d_Btp4xp6Zytq1_4m9VDmLGI1Pt_BAy8ukdAKK6WosEKrcat2Vrt25ITU0Sc7lagfltHx3yOsLG31r.dQTKwVBMnWxY_knl3T2UtaXC';
        Httprequest req=new httprequest();
        String domainName='chandru-dev-ed.my.salesforce.com ';
        String endPointURL='https://ap1.salesforce.com/services/data/v27.0/sobjects/Account';
        req.setendpoint(endPointURL);
        req.setHeader('Content-Type', 'application/xml; charset=utf-8');
        req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
        req.setmethod('POST');
       // req.setHeader('Authorization', 'Bearer ' +Access_Token);
        req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        system.debug('sessionid***'+userinfo.getsessionid());
        response=res.getbody();
        System.debug('****************res.getStatusCode();'+res.getStatusCode());
        System.debug('****************res.getbody();'+res.getbody());
        return null;
    }
}



User-added image

Thanks,
Kathir

 
Prabu BaskaranPrabu Baskaran
Hi Sunil,
 
Sunil02KumarSunil02Kumar
Hi Kathir,

Replace end point URL assignment in Httprequest with below code:
String endPointURL='https://chandru-dev-ed.my.salesforce.com/services/data/v27.0/sobjects/Account';

I am assuming chandru-dev-ed.my.salesforce.com is domain name of org for which you want access token.

If this also didn't work, it means there is issue with access token that you have specified.

If you specify https://ap1.salesforce.com/services/data/v27.0/sobjects/Account then salesforce refers to same instance from where you are sending request. So use domain name in URL so that it can differentiate different instance present in same domain.

Thanks,
Sunil Kumar

 
Sunil02KumarSunil02Kumar
Hi All,

You can refer below URL to understand how to get Access_Token of salesforce org:
http://sunil02kumar.blogspot.in/2015/04/access-token-using-auth-20-in-salesforce.html (http://sunil02kumar.blogspot.in/2015/04/access-token-using-auth-20-in-salesforce.html" target="_blank)

Thanks,
Sunil Kumar
Kathir DevanKathir Devan
Hi Sunil,

    I have created webservice  which was created  in your blogs it wrkg fine for me but not open salesforce org only new page is created.What do i missing.I have some doubt where do i get id, Outh code, Referesh token and signature plz see my screen shot given below..

User-added image

Thanks,
kathir
Sunil02KumarSunil02Kumar
Hi Kathir,

Add "Refesh Access Token" button on detail page. When you click on this button, infomation related to access token, refresh token will get populated automatically once you autorize the connection.

Thanks,
Sunil Kumar
SubbuSubbu
Please let me know about Access Key

String Access_Token='3MVG9Y6d_Btp4xp6Zytq1_4m9VDmLGI1Pt_BAy8ukdAKK6WosEKrcat2Vrt25ITU0Sc7lagfltHx3yOsLG31r.dQTKwVBMnWxY_knl3T2UtaXC';

Is it combination of consumer key, consumer secret and security token string as show below

Access_Token =  consumer key + consumer secret + security token string
SubbuSubbu
Please let me know about Access Key

String Access_Token='3MVG9Y6d_Btp4xp6Zytq1_4m9VDmLGI1Pt_BAy8ukdAKK6WosEKrcat2Vrt25ITU0Sc7lagfltHx3yOsLG31r.dQTKwVBMnWxY_knl3T2UtaXC';

above statement what is the assigned string  please let me know , I was sticked here. Please  I am waiting ..... Kindly help me
Thanks in advance
subbu
Sunil02KumarSunil02Kumar
Hi Subbu,

Access_Token will chage with time and it is used for authentication between different application in Oauth 2.0 and it is not combination of consumer key, consumer secret and security token.
In order to get access token, you need to send request to other application and after authentication, you will get access token in URL.

You can refer below URL to understand how to get Access_Token of salesforce org:
http://sunil02kumar.blogspot.in/2015/04/access-token-using-auth-20-in-salesforce.html (http://sunil02kumar.blogspot.in/2015/04/access-token-using-auth-20-in-salesforce.html" target="_blank)

You can also specify the sessionId instead of access_token of user in other application where you need to send request.

Thanks,
Sunil Kumar