Create below apex class for Community User Rest API login:
Apex Class:
/*
Author : Biswajeet Samal
Description : Community users login using rest API
*/
@RestResource(urlMapping='/CommunityLoginAPI/*')
global without sharing class CommunityLoginAPI {
/*
* Validate User login
* @param username : Login User Username
* @param password : Login User Password
* @param domain : Login domain instance ('login' for a prod/dev instance) and ('test' for a sandbox instance)
* @return LoginResponse : For login validate response message
*/
@HttpPost
global static LoginResponse login() {
LoginResponse objResponse = new LoginResponse();
String username = RestContext.request.params.get('username');
String password = RestContext.request.params.get('password');
String domain = RestContext.request.params.get('domain');
try{
string loginXML = '<?xml version="1.0" encoding="utf-8"?>';
loginXML += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">';
loginXML += '<soapenv:Header>';
loginXML += '<urn:LoginScopeHeader>';
loginXML += '<urn:organizationId>'+ UserInfo.getOrganizationId() +'</urn:organizationId>';
loginXML += '</urn:LoginScopeHeader>';
loginXML += '</soapenv:Header>';
loginXML += '<soapenv:Body>';
loginXML += '<urn:login>';
loginXML += '<urn:username>'+ username +'</urn:username>';
loginXML += '<urn:password>'+ password +'</urn:password>';
loginXML += '</urn:login>';
loginXML += '</soapenv:Body>';
loginXML += '</soapenv:Envelope>';
HttpRequest request = new HttpRequest();
request.setEndpoint('https://'+ domain +'.salesforce.com/services/Soap/c/44.0');
request.setTimeout(60000);
request.setMethod('POST');
request.setHeader('SOAPAction', 'login');
request.setHeader('Accept','text/xml');
request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
request.setBody(loginXML);
HttpResponse response = new Http().send(request);
String responseBody = response.getBody();
String sessionId = getValueFromXMLString(responseBody, 'sessionId');
objResponse.statusMessage = response.getStatus();
objResponse.statusCode = response.getStatusCode();
if(string.isNotBlank(sessionId)){
objResponse.isSuccess = true;
objResponse.sessionId = sessionId;
}else{
objResponse.isSuccess = false;
}
}
catch(System.Exception ex){
objResponse.isSuccess = false;
objResponse.statusMessage = ex.getMessage();
}
system.debug('objResponse-' + objResponse);
return objResponse;
}
/*
* Get XML tag value from XML string
* @param xmlString : String XML
* @param keyField : XML key tag
* @return String : return XML tag key value
*/
public static string getValueFromXMLString(string xmlString, string keyField){
String xmlKeyValue = '';
if(xmlString.contains('<' + keyField + '>')){
try{
xmlKeyValue = xmlString.substring(xmlString.indexOf('<' + keyField + '>')+keyField.length() + 2, xmlString.indexOf('</' + keyField + '>'));
}catch (exception e){
}
}
return xmlKeyValue;
}
global class LoginResponse {
public String sessionId {get; set;}
public Boolean isSuccess {get; set;}
public String statusMessage {get; set;}
public Integer statusCode {get; set;}
}
}
1. Create or Open Community and Activate
2. After community creation go to Sites | Click on Community Name | Public Aaccess Setting | Enabled Apex Class Access | Add above class “CommunityLoginAPI” | Save
Usually we make Rest API calls from Salesforce to External systems to get the data or to pass the updates to External Systems, using Apex class. But sometimes we can have a situation, like where we need to make a call to external systems from the visual force page.
Salesforce has introduced a concept called AJAX ToolKit, which help us to make REST API call from the JavaScript in Visualforce Page. Here is an example to invoke REST API from Visualforce Page. In below example I’m using https://exchangeratesapi.io/ web service HTTP callout and send a GET request to get the foreign exchange rates. The foreign exchange rates service sends the response in JSON format.
Visualforce Page:
<apex:page>
<apex:includeScript value="//code.jquery.com/jquery-1.11.1.min.js" />
<script>
function apiCall() {
//Get a reference to jQuery that we can work with
$j = jQuery.noConflict();
//endpoint URL
var weblink = 'https://api.exchangeratesapi.io/latest?base=USD';
$j.ajax({
url: weblink,
type: 'GET', //Type POST or GET
dataType: 'json',
beforeSend: function(request) {
//Add all API Headers here if any
//request.setRequestHeader('Type','Value');
},
crossDomain: true,
//If Successfully executed
success: function(result) {
//Response will be stored in result variable in the form of Object.
console.log('Response Result' + result);
//Convert JSResponse Object to JSON response
var jsonResp = JSON.stringify(result);
document.getElementById("apiData").innerHTML = jsonResp;
},
//If any Error occured
error: function(jqXHR, textStatus, errorThrown) {
//alert('ErrorThrown: ' + errorThrown);
}
});
}
</script>
<apex:form>
<!--call javaScript-->
<input type="button" value="Call API" onclick="apiCall()" />
<div id="apiData">
</div>
</apex:form>
</apex:page>
URL: /services/apexrest/AccountAPI?id=AccountId Method: Get
@RestResource (urlMapping='/AccountAPI/*')
global with sharing class AccountRESTService {
@HttpGet
global static Account getAccount() {
RestRequest req = RestContext.request;
String accountId = req.params.get('id');
Account acc = [SELECT Id, Name FROM Account WHERE Id =: accountId];
return acc;
}
}
URL: /services/apexrest/AccountAPI/AccountId Method: Get
@RestResource (urlMapping='/AccountAPI/*')
global with sharing class AccountRESTService {
@HttpGet
global static Account getAccount() {
RestRequest req = RestContext.request;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Account acc = [SELECT Id, Name FROM Account WHERE Id =: accountId];
return acc;
}
}
Inbound Web Service:
Inbound web service is when Salesforce exposes SOAP/REST web service, and any external/third party application consume it to get data from your Salesforce org. It is an Inbound call to Salesforce, but outbound call to the external system. Here, Salesforce is the publisher and external system is the consumer of web services.
Outbound Web Service:
Outbound web service is when Salesforce consume any external/third party application web service, a call needs to send to the external system. It is an Inbound call to the external system, but outbound call to Salesforce. Here, external system is the publisher of web services and Salesforce is the consumer.
There are two commonly used web service:
SOAP(Simple Object Access Protocol)
SOAP is a web service architecture, which specifies the basic rules to be considered while designing web service platforms.
It works over with HTTP, HTTPS, SMTP, XMPP.
It works with WSDL.
It is based on standard XML format.
SOAP Supports data in the form of XML only
SOAP API preferred for services within the enterprise in any language that supports Web services.
REST (Representational State Transfer)
REST is another architectural pattern, an alternative to SOAP.
It works over with HTTP and HTTPS.
It works with GET, POST, PUT and DELETE verbs to perform CRUD operations.
It is based on URI.
REST Supports both XML and JSON format.
REST API preferred for services that are exposed as public APIs and mobile, since JSON being Lighter the app runs smoother and faster.
/services/data/v39.0/tooling/query?q=Select Id,ValidationName,Active,Description,EntityDefinition.DeveloperName,ErrorDisplayField, ErrorMessage From ValidationRule WHERE EntityDefinition.DeveloperName = 'Account'
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject