salesforce data migration services

Learn How To Test Rest API 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” so I cannot resist sharing some great amount of knowledge for all new developers with this blog “Learn How To Test Rest API In Salesforce”.

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

Get Start To Test Rest API

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

[php]

/********************************************
* 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>();
}
}
}

[/php]

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

[php]

@HttpPost

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

[/php]

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

[php]
<blockquote>
@RestResource(urlMapping=’/v1/accounts/*’)
global with sharing class RESTWebservice
{

@HttpPost
global static Web_Referral__c Stringresponse
(RESTWebservice.AccountWrapper) {

Account acct = new Account();
acct.Name = WrapObj.name;
acct.Phone = WrapObj.phone;
acct.Website = WrapObj.website;
insert acct;
String AccountResponse;
String Web_Referral__c();
ResponseString.Put(‘Successfully Inserted:’+
acct.Id,acct);
}
Global class WebWrapper
{
Public String Name;
Public String Phone;
Public String Website;
PublicWebWrapper()
}

[/php]

Now Save your class which is now ready for testing.

As I mentioned before in this blog “Learn How To Test Rest API In Salesforce”, therefore let’s 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:

The First Class mentioned at the beginning use this JSON:

[php]
<blockquote>
{
"name" : "vinay",
"phone" : "9999345317",
"website" : "vinaychaturvedi.com"
}
</blockquote>
[/php]

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

[php]

{
"wrpVals":
{
"name" : "vinay",
"phone" : "9999345317",
"website" : "vinaychaturvedi.com"
}
}
[/php]

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

I 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 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.

 

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”.

I hope you enjoyed this blog “Learn How To Test Rest API In Salesforce” and I hope it helps you in your journey with REST API.

Stay Connected for more updates and amazing content from the world of Salesforce, crafted just for you!