Blog Categories

Posted by on Jun 22, 2017 in Featured, Tutorials | 0 comments

Learn how to test your Rest API’s in Salesforce

Learn how to test your Rest API’s in Salesforce

Being a Developer its a big plus having knowledge implementing Webservices and more complex is the environment to Test those. I very often come across questions about “Testing the REST API’s” so I cannot resist sharing some great amount of knowledge for all new developers with this blog “Learn how to test your Rest API’s in Salesforce”.

Everyone is aware about the two very common tools “Workbench” & “Postman”, these offer you some seriously amazing features to test your REST API’s. In this blog I’ll explain some working examples of the Same with building oAuth, Demo class, Basic JSON with examples and explanation.

Let’s Start:

Here is a Sample Apex Rest webservice that allows a Connected Application to push data into Salesforce.

/*******************************************************************************************
* Description – Apex REST service with GET and POST methods
* Author – Vinay

{
“name” : “Vinay”,
“phone” : “9999345317”,
“website” : “www.vinaychaturvedi.com”
}
********************************************************************************************/

@RestResource(urlMapping=’/v1/accounts/*’)
global with sharing class RESTWebserviceForAccount {

@HttpPost
global static AccountWrapper doPost(String name, String phone, String website) {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
AccountWrapper response = new AccountWrapper();

Account acct = new Account();
acct.Name = name;
acct.Phone = phone;
acct.Website = website;
insert acct;

response.acctList.add(acct);
response.status = ‘Success’;
response.message = ‘Your Account was created successfully.’;
return response;
}

@HttpGet
global static AccountWrapper doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
AccountWrapper response = new AccountWrapper();

String accountId = req.requestURI.substring(req.requestURI.lastIndexOf(‘/’)+1);

if(doSearch(accountId)) {
searchAccounts(req, res, response);
}
else {
findAccount(res, response, accountId);
}

return response;
}

// If the item to the right of the last forward slash is “accounts”, the request went to v1/accounts?Name=United
// Else the request went to v1/accounts/<something>, which is not a search, but a specific entity
private static boolean doSearch(String accountId) {
if(accountId == ‘accounts’) {
return true;
}
return false;
}

//If the request came to /v1/accounts, then we want to execute a search
private static void searchAccounts(RestRequest req, RestResponse res, AccountWrapper response) {

//Use the RestRequest’s params to fetch the Name parameter
String searchTerm = req.params.get(‘Name’);

if(searchTerm == null || searchTerm == ”) {
response.status = ‘Error’;
response.message = ‘You must provide a Name for your search term.’;
res.StatusCode = 400;
}
else {
String searchText = ‘%’+searchTerm+’%’;
List<Account> searchResults = [SELECT Id, Name, Phone, Website FROM Account WHERE Name LIKE : searchText];

if(searchResults != null && searchResults.size() > 0) {
response.acctList = searchResults;
response.status = ‘Success’;
response.message = searchResults.size() + ‘ Accounts were found that matched your search term.’;
}
else {
response.status = ‘Error’;
response.message = ‘No Accounts where found based on that Name, please search again.’;
}
}
}

//If the request came to v1/accounts/<external_Id>, then we want to find a specific account
private static void findAccount(RestResponse res, AccountWrapper response, String accountId) {

// Provided we recevied an External Id, perform the search and return the results
if(accountId != null && accountId != ”) {
List<Account> result = [SELECT Id, Name, Phone, Website FROM Account WHERE External_Id__c =: accountId];

if(result != null && result.size() > 0) {
response.acctList.add(result[0]);
response.status = ‘Success’;
}
else {
response.status = ‘Error’;
response.message = ‘This account could not be found, please try again.’;
res.StatusCode = 404;
}
}
// If the request came to /v1/accounts/ (without an Account Id), return an error
else {
response.status = ‘Error’;
response.message = ‘You must specify an External Id.’;
res.StatusCode = 400;
}
}

global class AccountWrapper {
public List<Account> acctList;
public String status;
public String message;

public AccountWrapper(){
acctList = new List<Account>();
}
}
}

FYI: This code may run into errors if the number of parameters may increase  above 32 max here at ==>

@HttpPost

global static AccountWrapper doPost(String name, String phone, String website)

In order to overcome the conflict I would suggest to use the @HttpPost method like this:

@RestResource(urlMapping=’/v1/accounts/*’)
global with sharing class RESTWebservice {

@HttpPost
global static map<String, Web_Referral__c>Stringresponse(RESTWebservice.AccountWrapper  WrapObj) {

Account acct = new Account();
acct.Name = WrapObj.name;
acct.Phone = WrapObj.phone;
acct.Website = WrapObj.website;
insert acct;

map<String, Account> ResponseString = new map<String, Web_Referral__c>();
ResponseString.Put('Successfully Inserted:'+' '+acct.Id,acct);
return Web.Id;

}

Global class WebWrapper 
{
   Public String Name;
   Public String Phone;
   Public String Website;
Public WebWrapper()
    { }

}

Now Save your class which is now ready for testing.

As I mentioned before in this blog “Learn how to test your Rest API’s in Salesforce”, therefore lets start testing the service we just created.

Using Workbench

Steps for Testing how to test @HttpPost Method:

  • Under “Choose an HTTP method to perform on the REST API service URI below: select Http Post Verb.
  • In the url-box enter this URL: ” /services/apexrest/v1/Account/”
  • In the Request Body textbox enter below json:

For The First Class mentioned at the beginning use this Json:

{
“name” : “vinay”,
“phone” : “9999345317”,
“website” : “vinaychaturvedi.com”
}

For The Second Class mentioned below the Topmost Class use this Json:

{
"wrpVals":
   {
      "name" : "vinay",
      "phone" : "9999345317",
      "website" : "vinaychaturvedi.com"
   }
}

Check the below Image:

  • Click Execute and check the data inserted under Account Object

Steps for Testing @HttpGet Method :

  • Repeat step 1 & 2 from above
  • Under “Choose an HTTP method to perform on the REST API service URI below: select Http Get Verb.
  • In the url-box enter this URL: ” /services/apexrest/v1/Account/ Vinay

Hope you got it right.

Now let’s begin our Journey towards

Testing REST web service using POSTMAN Client

In the Salesforce Instance where the Above classes are create a Connected App, give it any name of your choice and give the Callback URL as:

“https://www.getpostman.com/oauth2/callback”

Give the permissions of your choice, here are the ones I gave:

  • Access your basic information (id, profile, email, address, phone)
  • Access and manage your data (api)
  • Full access (full)

Now Save and don’t forget to copy the Consumer Key and Consumer Secret keys.

Steps to test:

Download the Postman Client or Add the Extension from Google Play and follow the steps below:

 

Step 1. Open the Postman Client and Click on Collections from the topmost menu ==> Click New Collection==> Give a Name and Save.

Next ==>

Step 2. Now Click on the collection we just created and then Click “Authorization” and the Type to “oAuth 2.0”.

Step 3. Now Click on Get Access token.

Auth url: https://test.salesforce.com/services/oauth2/authorize

Access Token url: https://test.salesforce.com/services/oauth2/token

Username is: yourSalesforceusername

Password is: SalesforcePassword

Click on Request Token and you will receive the Access Token, Select the Last Token from the List under Named Existing Tokens ==> Click Use Token

Next Click on Save.

Then Select the Collection name where Token name should be saved

Now the authentication is all set and working, so let’s start sending a Post request.

  • Select the method as “Post”.

  • Change the url to: “your Salesforce Instance Name/”+“services/apexrest/”+“Custom Url Mapping from the Classes we created/”
  • Now Click on Body, Under the Body Click Raw,  and from the Dropdown select Json(Application/Json).

Check the Image below

  • Paste your JSON in the box below and Click Send and View the Response.

Isn’t that amazing and simple, that’s the reason I preferred to go step-wise taking screenshots and try to explain the best way using the visuals as “The Visual memory is the strongest Memory”.

Hope you enjoyed this blog “Learn how to test your Rest API’s in Salesforce”  and I hope it helps you in your journey with REST API’s.

Stay Connected for more updates and amazing content from the world of Salesforce, crafted just for you, also, do not forget to share and tweet this blog and help others find the right content.

Post a Reply

Your email address will not be published. Required fields are marked *