REST

Apex Rest inbound:
 
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
 
    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account account = [SELECT Id FROM Account WHERE Id = :accountId];
        delete account;
    }
  
    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
        return result;
    }
  
  @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;
    }
}

Apex Rest callout - GET:

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}

Apex Rest callout - POST:

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
        response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}




REST Inbound Web Service:

/*************
Workbench rest post url: /services/apexrest/RestServiceContactCreation
Request Body:
{
"req": {
"contactLastName" : "Test",
"contactEmail" : "test@test.com",
"contactPhone" : "1212121212"
}
}
***************/

@RestResource(urlMapping='/RestServiceContactCreation/*')
global class RestServiceContactCreation{
    global class ContactRequestDetails{
        webservice String contactLastName;
    }
    
    global class ContactResponseDetails{
        webservice String contactLastName;
        webservice String contactCreationStatus;
    }
    
    global static ContactResponseDetails insertContactDetails(ContactRequestDetails contRequest){
        ContactResponseDetails contResp = new ContactResponseDetails();
            Contact contactObject = new Contact();
            contactObject.LastName = contRequest.contactLastName;
            try
            {
                insert contactObject;
                contResp.contactCreationStatus = 'Contact is created successfully....!!!!! Contact Id: ' +contactObject.Id;
                return contResp;
                }
            catch(Exception ex){
                String errorMessage = 'Error occurred' +ex.getMessage();
                contResp.contactCreationStatus = errorMessage;
                return contResp;
            }
    }
    
    @HttpPost    
    global static ContactResponseDetails createContact(ContactRequestDetails req){
        ContactResponseDetails res = insertContactDetails(req);
        return res;
    }
}

REST Outbound Web Service:

public with sharing class RestServiceContactCreation_Outbound {
   public String contactPhone { get; set; }

    public String contactEmail { get; set; }

    public String contactLastName { get; set; }

    public String contReq { get; set; }
    
    public String response{get;set;}
    
    public class ContactRequestDetails{
        String contactLastName;
        String contactEmail;
        String contactPhone;
    }
    
    public PageReference CreateContact() {
        ContactRequestDetails contReq = new ContactRequestDetails();
        //find access token using Auth 2.0 
        String Access_Token='00D28000000JPGf!AQ8AQJH27ODTW8k4SQz1wd5zKMXKX7D7tGwmjkyETuNjdwgl94yIeBN8QFpVlRQg_xQWeEpBjhtKjWVurcU.EQUP0ND3Jovp';
        //String username = 'sohel@sf.com';
        //String password = 'so123';

        Httprequest req=new httprequest();
        String endPointURL='https://mohd-sohel-dev-ed.my.salesforce.com/services/apexrest/RestServiceContactCreation/';
        //String endPointURL='https://mohd-sohel-dev-ed.my.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>'+contactLastName+'</name><email>'+contactEmail+'</email><phone>'+contactPhone+'</phone> </request>');
        req.setmethod('POST');
        
        //Blob headerValue = Blob.valueOf(username + ':' + password);
        //String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
        //req.setHeader('Authorization', authorizationHeader);

        
        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;
    }
}



public class RestAccessToken{

      String clientId = '3MVG9ZL0ppGP5UrA4TZvGuLjTutN5TE6THQxE53nMJd9xaFHRwUo1nLeqlO2959DxwwkKcPHq.Att.LAs77OS';
    
    //Use your Client Secret
    String clientsecret='7065315749695222886';
    
    //Your Destination org username
    String username='sohel@sf.com';
    
    //Your Destination orgPassword+Security Token
    String password='so123ShfcYbmBsSe3XN6zaDosuyVzl';
    
    String accesstoken_url='https://login.salesforce.com/services/oauth2/token';
    String authurl='https://login.salesforce.com/services/oauth2/authorize';
    
    public class deserializeResponse {
    public String id;
    public String access_token;
    }
    public String ReturnAccessToken(RestAccessToken Acc){
    String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
    Http h= new Http();
    HttpRequest req= new HttpRequest();
    req.setBody(reqbody);
    req.setMethod('POST');
    //Change "ap4" in url to your Destination Org Instance
    req.setEndpoint('https://ap6.salesforce.com/services/oauth2/token');
    HttpResponse res=h.send(req);
    System.debug(res.getBody()+'By-AP-1986-Response');
    deserializeResponse resp1= (deserializeResponse)JSON.deserialize(res.getBody(),deserializeResponse.class);
    System.debug(resp1+'By-AP-deserializeresponse');
    System.debug(resp1.access_token+'Access token');
    return resp1.access_token;
    }
    
}

No comments:

Post a Comment