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

Monday, 23 June 2014

TEST Class for REST API Call.

Writing TEST class for REST API

If you want to have a reference for how to write REST API, please use the below link.

http://priyamohanraj.blogspot.in/2014/05/calling-rest-api-in-salesforce.html

we should first write the MOCK Class for the http Request.

MOCK REQUEST FOR TEST CLASS

@isTest
global class Mockhttpcallouts implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req)
    {
        system.debug('------------------'+req);
        HttpResponse res = new HttpResponse();
        System.assertEquals('GET', req.getMethod());
        res.setHeader('Content-Type', 'application/json');
        res.setBody('[{"FirstName" : "test","LastName" : "data1","Email" : "test.data1@email.com","Title" : "Mr"},{"FirstName" : "test","LastName" : "data2","Email" : "test.data2@email.com","Title" : "Miss"},{"FirstName" : "test","LastName" : "data3","Email" : "test.data3@email.com","Title" : "Mr"},{"FirstName" : "test","LastName" : "data4","Email" : "test.data4@email.com","Title" : "Miss"},{"FirstName" : "test","LastName" : "data5","Email" : "test.data5@email.com","Title" : "Mr"}]');
        system.debug('------------INSIDE IF-------------');
        res.setStatusCode(200);
         
     
}
}

Now test class for the API Class

The above call will execute whenever Account record is insert, it will trigger this API call and get the contact data and insert the contact data into salesforce.

@isTest(seeAlldata =false)
public class TestExternal_APITrg
{
   @isTest static void APIClass_Test()
   {
  Account ac = new Account();
  ac.Name = 'Test Account';
  ac.CountryName__c = 'India';
  Insert ac;
  Test.startTest();
       Test.setMock(HttpCalloutMock.class, new Mockhttpcallouts());
       try
       {
        APIClass.JSONAPICall(ac);
       }
       catch (System.CalloutException e){
System.debug('ERROR:' + e);
}
}
}

Friday, 23 May 2014

Calling REST API in salesforce

Hi

Today we can see about calling REST API in salesforce.

Step 1 :

If you want to call the REST API in salesforce, first we need to add that URL into Remote Stie Settings.

Goto setup ->Administration setup ->security Controls-> Remote site settings

Click on New
Give the name and Url in the Remote site page and click on save.

Once this URL is saved, we have to write a apex class to call this REST API. Rest API will return the JSON string, below is the JSON String. below is the array of data. if you have square bracket in your JSON then it is returning the array of the data.

String jsonString = '[ {
 "FirstName" : "test",
 "LastName" : "data1",
 "Email" : "test.data1@email.com",
 "Title" : "Mr"
 },
 {
 "FirstName" : "test",
 "LastName" : "data2",
 "Email" : "test.data2@email.com",
 "Title" : "Miss"
 },
 {
 "FirstName" : "test",
 "LastName" : "data3",
 "Email" : "test.data3@email.com",
 "Title" : "Mr"
 },
 {
  "FirstName" : "test",
 "LastName" : "data4",
 "Email" : "test.data4@email.com",
 "Title" : "Miss"
 },
 {
 "FirstName" : "test",
 "LastName" : "data5",
 "Email" : "test.data5@email.com",
 "Title" : "Mr"
 } ] ';

To get this JSON, we need to send http request, to get the data via REST API.

below is the code which is used to fetch the data frm REST API

 global class APIClass
 {
   @future(callout=true)
   public static void JSONAPICall(Account ac)
   {
  Http h = new Http();
  HttpRequest req = new HttpRequest();
  req.setMethod('GET');
  string url='                                                          ';
  req.setEndpoint(url);
  HttpResponse res = h.send(req);
  JSONParser parser = JSON.createParser(res.getBody());
  list<contact> contactsdata = new List<contact>();
        JSONParser parser = JSON.createParser(jsonstr);
        while (parser.nextToken() != null)
        {
            if (parser.getCurrentToken() == JSONToken.START_ARRAY)
            {
         
                while (parser.nextToken() !=  JSONToken.END_ARRAY)
                {
                    if (parser.getCurrentToken() == JSONToken.START_OBJECT)
                    {                    
                        contact ci = new contact();
                        while (parser.nextToken() !=  JSONToken.END_OBJECT)
                        {                        
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'title'))
                                {
                                    parser.nextToken();
                                    ci.title = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'firstname'))
                                {
                                    parser.nextToken();
                                    ci.firstname = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'lastname'))
                                {
                                    parser.nextToken();
                                    ci.lastname = parser.getText();
                                }
                                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText().tolowercase() == 'email'))
                                {
                                    parser.nextToken();
                                    ci.email = parser.getText();
                                }
if(ac != null)
ci.AccountId = ac.Id;
                         
                        }
                        contactsdata.add(ci);
                    }
                }
            }
        }
  if(contactsdata.size() > 0)
  {
   insert contactsdata;
  }
    }

  }

In the URL you have give your API URL, and out put of the API URL is JSON Data. After fetching the data we are inserting the data into contact object.


Monday, 11 November 2013

Simple REST API

Below is the steps to execute the REST Code in Salesforce.


STEP 1 : 

If you are using windows environment, we have to get the CURL to be installed in your machine.

URL to install the cURL is http://www.confusedbycode.com/curl/#downloads 


STEP 2: 

Set the Remote Access in Salesforce.

Click on setup -> create->Apps. In the Connected Apps Section click on New. 






Fill all the above details and click on save. once you have saved, you will get the consumer key and consumer secret. 



STEP 3:

Generate the Access Token to execute the RESTAPI

Go to CMD and execute the following code.

curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=consumerkey" -d "client_secret=consumerSecret" -d "username=salesforceUsername" -d "password=password+securitytoken"

OUTPUT



STEP 4 : 

Create the REST API Class in Salesforce.

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

STEP 5:

To call the do get method from a client, open a command-line window and execute the following cURL command to retrieve an account by ID:

curl -H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"

    Replace sessionId with the Access Token element that you will get that on STEP 3 as a result.
    Replace instance with your <serverUrl> element.
    Replace accountId with the ID of an account which exists in your organization.

OUTPUT:

{
"attributes":{
"type" : "Account",
"url" : "/services/data/v29.0/sobjects/Account/001XXXXXXX"
},
"Name" : "TEST DATA",
"Id": "001XXXXXXXXX"
}