Skip to main content

How to Build a Basic Salesforce REST API (With Test Class)

How to Build a Basic Salesforce REST API (With Test Class) and Test with POSTMAN


Salesforce : Creating Anonymous Apex REST APIs with Force.com

The Force.com REST API lets you integration with Force.com applications using standard HTTP methods. This API provides a way to expose the data you have within your Force.com application to external applications – both mobile and non-mobile. A few useful bits of information related to these REST APIs:
This sample Code you how to implement a simple REST API to fetch Account in Apex class:

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
    @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;
    }
}


Call to REST Client (with Curl) : curl -H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"
Replace sessionId with the element that you noted in the login response.
Replace instance with your element.
Replace accountId with the ID of an account which exists in your organization.
After calling the doGet method, Salesforce returns a JSON response with data such as the following:

{
  "attributes" : 
    {
      "type" : "Account",
      "url" : "/services/data/v22.0/sobjects/Account/accountId"
    },
  "Id" : "accountId",
  "Name" : "Acme"

}

This sample Code you how to implement a simple REST API to fetch Account in Apex that handles two different HTTP request methods (Commonly Used) :

@RestResource(urlMapping='/Account/*')
global with sharing class RestAccountController {
    @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 Account doPost(string accountId) {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
        return result;
    }

    @HttpPost
    global static Account doPost(){
        String accountId = RestContext.request.requestBody.toString();
        Account acc = [SELECT Id FROM Account WHERE id =: accountId];
        return acc;        
    }

}

Create a file called account.txt to contain the data for the account you will create in the next step. (For JSON in POSt Data) curl -H "Authorization: Bearer sessionId" -H "Content-Type: application/json" -d @account.txt "https://instance.salesforce.com/services/apexrest/Account/"
Replace sessionId with the element that you noted in the login response.
Replace instance with your element.
Replace accountId with the ID of an account which exists in your organization.
After calling the doGet method, Salesforce returns a JSON response with data such as the following:

{
  "attributes" : 
    {
      "type" : "Account",
      "url" : "/services/data/v22.0/sobjects/Account/accountId"
    },
  "Id" : "accountId",
  "Name" : "Acme"

}

Test Class for REST API in Salesforce

@isTest
public class RestAccountControllerTest {
    @testSetup static void setup() {
        Account ac = (Name='TradePortal') ;
        insert ac;        
    }
    @isTest
    static void RestAccountControllerGetProcess(){      
        Account acc = [SELECT Id FROM Account LIMIT 1];
        RestRequest request = new RestRequest();
        request.requestUri =https://instance.salesforce.com/services/apexrest/Account/'+acc.Id;
        request.httpMethod = 'POST';
        RestContext.request = request;
        RestAccountController.doGet();        
        
    }
    @isTest
    static void RestAccountControllerPostProcess(){     
        Account acc = [SELECT Id FROM Account LIMIT 1];
        RestRequest request = new RestRequest();
        request.requestUri =https://instance.salesforce.com/services/apexrest/Account';
        request.httpMethod = 'POST';
        request.addHeader('Content-Type', 'application/json'); 
        RestContext.request = request;
        RestAccountController.doPost(acc.Id);        
    }
}

Test With Postman REST Client :

Resource after Before request to REST API

Session Id for Authorization : "Authorization: Bearer sessionId" Replace sessionId with the element that you noted in the login response.
Server Instance URL of ORG : "https://instance.salesforce.com/services/apexrest/Account/" Replace instance with yourelement.
accountId : Replace accountId with the ID of an account which exists in your organization.

For Get :

For POST :

Happy Sharing...

Comments

Popular posts from this blog

Salesforce UNABLE_TO_LOCK_ROW: unable to obtain exclusive access to this record

Unable to lock row - Record currently unavailable errors Description When a record is being updated or created, we place a lock on that record to prevent another operation from updating the record at the same time and causing inconsistencies on the data. These locks normally last for a few seconds and when the lock is released, other operations can do whatever processing they are supposed to do on the record in question. However, a given transaction can only wait a maximum of 10 seconds for a lock to be released, otherwise it will time out. Resolution What and when records get locked depends on the operation you are performing and the main record you are working on. The  Force.com Record Locking Cheatsheet   provides detailed information on this and it's highly recommended that you familiarize yourself with its contents. Common Scenarios that prevent unlocking record a. Email-To-Case When an email is processed by email-to-case, triggers on the email mes...
Entitlement Processes for Salesforce Entitlement for the cases gives you automated solution for the SLA's. To overcome user’s manual work and automate business processes to send notifications on escalations within response times. We will go step by step to configure the Entitlements as Below. 1.         Search ‘Entitlement Settings’ from Quick search. It’ll enable Entitlement Process for your org. 2.         Now Go to ‘Milestones’. Create new Milestone. Example – Let’s say, Priority field on Case has values as Low, Medium and High. If Case has SLA as A.        If Priority is ‘Medium’ on case and the case is not Closed in next 8 hrs then it will escalate and send the Email notification. B.        If Priority is ‘High’ on case and the case is not Closed in next 4 hrs then it will escalate and send the Email notification. In...