Showing posts with label Rest Explorer. Show all posts
Showing posts with label Rest Explorer. Show all posts

Friday, March 5, 2021

Salesforce and java integration with rest api

Before starting salesforce java integration, let's discuss the requirements needed to integrate java and salesforce with rest api. 

There are five variables in code which you need to understand what they are :

1.) userName  = Username of salesforce credentials.

2.) passWordAndToken = Password of salesforce and security token combined without any space. If your password is ABC and token is 123 then passWordAndToken is ABC123. You can generate token by My setting => Personal => Reset my security token

3.) loginEnvUrl = If you want to login production then loginEnvUrl is "https://login.salesforce.com" but if you want to login production then loginEnvUrl is "https://test.salesforce.com".

4.) clientId and clientSecret = You can get clientId and clientSecret by setup => create => Apps => connected apps

Connected Apps Salesfore


Client Key and Client Secret


Jars required :

You will need four jar files for this integration and the four jars are required otherwise you will get an error. I am providing the link to all the jar files you can download from here.

Salesforce_Java_Integration_Jars


Java Code :

package Integration;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
public class Salesforce_Java_Integration {

public Salesforce_Java_Integration()
{
final String baseUri;
final Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
final Header oauthHeader;
final String userName  = "n*********gmail.com";               
final String passWordAndToken  = "***************************";    
final String loginEnvUrl  = "https://login.salesforce.com";
final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
final String clientId     = "3MVG97quA*************************bfh";
final String clientSecret = "7117DE190*****************FD40809299AE";

HttpResponse response = null;
HttpClient httpclient = HttpClientBuilder.create().build();
// Create login request URL
String loginURL = "";
try {
loginURL = loginEnvUrl + GRANTSERVICE +
"&client_id="+URLEncoder.encode(clientId, "UTF-8")+
"&client_secret=" +clientSecret +"&username=" +
URLEncoder.encode(userName, "UTF-8") +
"&password=" +URLEncoder.encode(passWordAndToken , "UTF-8");

System.out.println("loginURL---- "+loginURL);
HttpPost httpPost = new HttpPost(loginURL);
{
// POST request to Login
response = httpclient.execute(httpPost);
if(null!=response) {
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
System.out.println("Login Successfull");
}
else{
System.out.println("Error whie Login");
}
String getResult = null;
getResult = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = null;
String loginAccessToken = null;
String loginInstanceUrl = null;
jsonObject = (JSONObject)
                                                              new JSONTokener(getResult).nextValue();
loginAccessToken = jsonObject.getString("access_token");
loginInstanceUrl = jsonObject.getString("instance_url");
baseUri = loginInstanceUrl;
oauthHeader = new BasicHeader("Authorization", "OAuth "
                                                    + loginAccessToken) ;
// release connection
httpPost.releaseConnection();
System.out.println("oauthHeader===>>>"+oauthHeader);
System.out.println("prettyPrintHeader===>>>"+prettyPrintHeader);
System.out.println("baseUri===>>>"+baseUri);
}
else {
System.out.println("Please check your internet connection !!!");
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(final String[] args)
{
@SuppressWarnings("unused")
Salesforce_Java_Integration Integration = new Salesforce_Java_Integration();
}
}


OutPut:

Java Salesforce Integration

Now with the help of outhHeder, PrettyPrintHeader and baseUri you can get and set data in salesforce.


Thanks, 
Lovesalesforceyes



Thursday, March 4, 2021

Publish knowledge articles with rest api in salesforce

Whenever you create an article in salesforce its publish status is 'draft' by default. You have to publish that article to make it 'online'. In this blog we will learn how to publish draft article in salesforce by Rest API with the help of workbench :

Publish Draft article :

Here I am publishing one draft article. As you can see there is one one draft article in my org.

Draft articles in salesforce


First you need to find articleVersionId of the article which you want to publish. To get the articleVersionIdList you have to query on the KnowledgeArticleVersion object.

"SELECT KnowledgeArticleId, Id, PublishStatus, Title, UrlName FROM KnowledgeArticleVersion"

soql to get knowledgeVersionId


Method :- Post
URL:- /services/data/v50.0/actions/standard/publishKnowledgeArticles

Request Body :-
                        {
                            "inputs" : [
                             {
                                "articleVersionIdList" : [ "ka02x000000WGbwAAG" ],
                                 "pubAction" : "PUBLISH_ARTICLE"
                             }
                             ]
                         }

 

If you want to mass publish articles, you have to give comma separated id's in articleVersionIdList value in the request body.

Publish knowledge articles with workbench

Article Published:-  After executing the rest service, you can see the article is published now.

published articles in salesforce

Thanks, 
Lovesalesforceyes


Sunday, February 14, 2021

Insert attachments in salesforce with rest api

In this blog we will learn how to insert file type attachment in salesforce by Rest API with the help of workbench :

There is basically four subfields of file field in salesforce :

  1.  FieldName__Name__s  : Name of the attachment file.
  2.  FieldName__Body__s  :  Body of the attachment file.
  3.  FieldName__Length__s  : Length of the attachment file.
  4. FieldName__ContentType__s  : Type of the attachment file.  It is a picklist field which means it accepts only the values that are listed in picklist values. It has values like :
    application/html
    application/java-archive
    application/javascript
    application/msword
    application/octet-stream
    application/octet-stream;type=unknown
    application/pdf .... etc....

When inserting attachment with rest api only three subfields are required Name, Body and ContentType. Length will automatically generated after insertion of record. In The place of  Body__s subfield you have to give Base64 of that file which you want to insert. In the place of Name__s you have to give the name of the file and In the place of  ContentType__s you have to give the type of that file. Let's get Start :

Create a record with attachment :

Here i am creating one record with and inserting text file as attachment :

Method :- Post
URL:- /services/data/v50.0/sobjects/Knowledge__kav
Request Body :-

Insert attachment with rest api salesforce

In the place of Attachment__Body__s , I am giving converted base64 of text file.

Response :-

insert attachment with rest api salesforce

Record Created:-

insert attachment in salesforce


Thanks, 
Lovesalesforceyes

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...