Restful API in Salesforce Create & Consume both
@RestResource(urlMapping='/MyService/*')
global with sharing class RestAPIService {
@HttpGet
global static String doGet() {
List<countryies__c> obj = [Select ID,Name from countryies__c];
String data='';
for(countryies__c item:obj)
{
data += 'ID is '+ item.id + 'Name is ' + item.Name + '\n';
}
return data;
}
@HttpPost
global static String doPost(String name) {
countryies__c obj = new countryies__c();
obj.Name=name;
insert obj;
return 'Country ' + name + ' Added';
}
@HttpPut
global static String putAPI(String oname,String name) {
countryies__c obj = [Select ID,Name from countryies__c where Name=:oname limit 1];
obj.Name=name;
update obj;
return 'Hello PUT API EXAMPLE';
}
@HttpDelete
global static String deleteAPI() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
Id r = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
countryies__c obj = [Select ID,Name from countryies__c where Id=:r limit 1];
delete obj;
return 'Hello Delete' + r;
}
}
Consume Rest Services under APEX :
public with sharing class ConsumeAPI {
@AuraEnabled
public static String testGetAPI() {
Http http = new Http();
HttpRequest request = new HttpRequest();
// Dynamic org base URL
String baseUrl = URL.getOrgDomainUrl().toExternalForm();
String endpoint = baseUrl + '/services/apexrest/MyService';
request.setEndpoint(endpoint);//url
request.setMethod('GET');
// Add session header
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
request.setTimeout(60000);
HttpResponse response = http.send(request);
System.debug('👉 Status Code: ' + response.getStatusCode());
System.debug('👉 Response Body: ' + response.getBody());
if (response.getStatusCode() == 200) {
return response.getBody();
} else {
return '{"error": "API call failed with status ' + response.getStatusCode() +
', message: ' + response.getBody() + '"}';
}
}
@AuraEnabled
public static String testPOSTAPI(String name) {
Http http = new Http();
HttpRequest request = new HttpRequest();
// Dynamic org base URL
String baseUrl = URL.getOrgDomainUrl().toExternalForm();
String endpoint = baseUrl + '/services/apexrest/MyService';
request.setEndpoint(endpoint);//url
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
// Add session header
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
String jsonBody = '{"name":"'+name+ '"}';
request.setBody(jsonBody);
request.setTimeout(60000);
HttpResponse response = http.send(request);
System.debug('👉 Status Code: ' + response.getStatusCode());
System.debug('👉 Response Body: ' + response.getBody());
if (response.getStatusCode() == 200) {
return response.getBody();
} else {
return '{"error": "API call failed with status ' + response.getStatusCode() +
', message: ' + response.getBody() + '"}';
}
}
@AuraEnabled
public static String testPUTAPI(String oname,String name) {
Http http = new Http();
HttpRequest request = new HttpRequest();
// Dynamic org base URL
String baseUrl = URL.getOrgDomainUrl().toExternalForm();
String endpoint = baseUrl + '/services/apexrest/MyService';
request.setEndpoint(endpoint);//url
request.setMethod('PUT');
request.setHeader('Content-Type', 'application/json');
// Add session header
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
String jsonBody = '{"oname":"'+ oname +'","name":"'+ name +'"}';
request.setBody(jsonBody);
request.setTimeout(60000);
HttpResponse response = http.send(request);
System.debug('👉 Status Code: ' + response.getStatusCode());
System.debug('👉 Response Body: ' + response.getBody());
if (response.getStatusCode() == 200) {
return response.getBody();
} else {
return '{"error": "API call failed with status ' + response.getStatusCode() +
', message: ' + response.getBody() + '"}';
}
}
@AuraEnabled
public static String testDELETEAPI() {
Http http = new Http();
HttpRequest request = new HttpRequest();
// Dynamic org base URL
String baseUrl = URL.getOrgDomainUrl().toExternalForm();
String endpoint = baseUrl + '/services/apexrest/MyService/a0ZdM000003RnCbUAK';
request.setEndpoint(endpoint);//url
request.setMethod('DELETE');
request.setHeader('Content-Type', 'application/json');
// Add session header
request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
request.setTimeout(60000);
HttpResponse response = http.send(request);
System.debug('👉 Status Code: ' + response.getStatusCode());
System.debug('👉 Response Body: ' + response.getBody());
if (response.getStatusCode() == 200) {
return response.getBody();
} else {
return '{"error": "API call failed with status ' + response.getStatusCode() +
', message: ' + response.getBody() + '"}';
}
}
public static void postDataIntoAPI(String name,String email,String gender,String status) {
try
{
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://gorest.co.in/public/v2/users');
request.setMethod('POST');
// Headers
request.setHeader('Content-Type', 'application/json');
request.setHeader('Authorization', 'Bearer c1c7fa5775f13f847f27051131afb2621a0cb317ee666d28e3e88d22defcc5b8');
// Proper JSON body
String jsonBody = '{"name":"'+name+'","email":"'+email+'","gender":"'+gender+'","status":"'+status+'"}';
request.setBody(jsonBody);
// Send request
HttpResponse response = http.send(request);
System.debug('Status: ' + response.getStatus());
System.debug('Body: ' + response.getBody());
}
catch(Exception ex)
{
}
}
public static void putDataIntoAPI(integer id,integer uid,String title,String body) {
try
{
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://jsonplaceholder.typicode.com/posts/'+id);
request.setMethod('PUT');
request.setHeader('Content-Type', 'application/json');
request.setBody('{"title":"'+title+'","body":"'+body+'","userId":'+uid+'}');
HttpResponse response = http.send(request);
System.debug('Status: ' + response.getStatus());
System.debug('Body: ' + response.getBody());
}
catch(Exception ex)
{
}
}
public static void deleteDataIntoAPI(integer id) {
try
{
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://jsonplaceholder.typicode.com/posts/'+id);
request.setMethod('DELETE');
request.setHeader('Content-Type', 'application/json');
HttpResponse response = http.send(request);
System.debug('Status: ' + response.getStatus());
System.debug('Body: ' + response.getBody());
}
catch(Exception ex)
{
}
}
@AuraEnabled
public static String getUsersFromAPI() {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://jsonplaceholder.typicode.com/users');
// request.setEndpoint('callout:JSONPLACEHODLER');
request.setMethod('GET');
HttpResponse response = http.send(request);
if(response.getStatusCode() == 200) {
return response.getBody();
/* List<Object> users = (List<Object>) JSON.deserializeUntyped(response.getBody());
for(Object obj : users) {
Map<String, Object> user = (Map<String, Object>) obj;
System.debug('Name: ' + user.get('name'));
System.debug('Email: ' + user.get('email'));
}*/
}
else {
return '{"error": "API call failed with status ' + response.getStatusCode() + '"}';
}
}
}
Consume RestAPI under outside of salesforce under postman
1) Login into postman.com
2) create workspace
3) search Salesforce Platform API
4) enable CORS setting in salesforce with postman.com & postman.co
5) Salesforce Platform API Auth 2.0 click on it
6) Click on AUTH and go into bottom and click on GET NEW ACCESS TOKEN Button
7) Authorize then it provide use token click on it
8) copy url and set into endpoint under variable section
9) go into RestAPI and call your url like this way
{{_endpoint}}/services/apexrest/MyService
Without Endpoint variable
https://shivaconceptsolution-dev-ed.develop.my.salesforce.com/services/apexrest/MyService/a0ZdM000003RnCbUAK
Comments
Post a Comment
POST Answer of Questions and ASK to Doubt