RESTful API in Salesforce: The Complete Guide

Think of a REST API as the digital waiter in a restaurant. You, the Client don't just walk into the kitchen and grab what you want; instead, you place a formal HTTP Request through a standardized menu. This request tells the Server exactly what you need using a specific Endpoint and an HTTP Method like GET, POST or DELETE.



Make API Callout In Salesforce

public static void callAPI() { // Define the URL before using it String url = 'https://www.themealdb.com/api/json/v1/1/search.php?s=pizza'; // Instantiate a new Http object Http h = new Http(); // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint HttpRequest req = new HttpRequest(); req.setEndpoint(url); // Set the URL endpoint req.setMethod('GET'); // Set the HTTP method // Set headers correctly using separate setHeader calls // req.setHeader('X-Key', 'Your API-Key'); // Send the request and get response HttpResponse res = h.send(req); // You can process the response here as needed System.debug(res.getBody()); }



What we can do with REST API in Salesforce
  • Basic Data Operations (CRUD)
  • Powerful Querying and Searching using SOQL and SOSL
  • Accessing Metadata
  • Specialized Salesforce APIs
  • Custom Apex REST Endpoints

Create (POST)
To add a new lead, you send a POST request to the SObject endpoint.
Endpoint: /services/data/v60.0/sobjects/Lead/
Action: You provide the Lead's details (Name, Company, Email) in the JSON Body.
Result: Salesforce creates the record and sends back a 201 Created status with the new Record ID.

Read (GET)
To pull account details, you use a GET request. You can either ask for a specific ID or use a SOQL Query.
Endpoint (Specific): /services/data/v60.0/sobjects/Account/{Account_ID}
Endpoint (Query): /services/data/v60.0/query/?q=SELECT+Name+FROM+Account
Result: Salesforce sends a 200 OK status with the account data in a JSON package.

Update (PATCH)
To change a deal's status, you use a PATCH request. Unlike a full replacement, PATCH only updates the fields you specify.
Endpoint: /services/data/v60.0/sobjects/Opportunity/{Opp_ID}
Action: In the JSON Body, you might just send {"StageName": "Closed Won"}.
Result: Salesforce updates that specific field and returns a 204 No Content (meaning "Update successful, nothing more to show”).

Delete (DELETE)
To remove an outdated record, you use the DELETE method.
Endpoint: /services/data/v60.0/sobjects/Lead/{Lead_ID}
Result: The record is moved to the Recycle Bin, and you get a 204 No Content confirmation.

Custom Apex REST Endpoints

RestRequest req = RestContext.request;  

RestResponse res = RestContext.response;

Use Rest Service

@RestResource(urlMapping='/MyAccountService/*')

global with sharing class MyRestResource {


    // 1. READ (GET) - Logic to fetch an account based on the URL ID

    @HttpGet

    global static Account getAccount() {

        RestRequest request = RestContext.request;

        // Grab the Account ID from the end of the URL: ../MyAccountService/001xxxxxx

        String accountId = request.requestURI.substring(

            request.requestURI.lastIndexOf('/') + 1

        );

        

        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];

        return result;

    }


    // 2. CREATE (POST) - Logic to insert a new account

    @HttpPost

    global static String createAccount(String name, String phone, String website) {

        Account newAcc = new Account(

            Name = name,

            Phone = phone,

            Website = website

        );

        insert newAcc;

        return 'Success! New Account ID: ' + newAcc.Id;

    }

}


Authorising and accessing the custom APIs from external system

Step1: Create Connected Apps
- Check on the Enable OAuth Settings.
The Callback URL you supply here is the same as your Web application’s callback URL. In this case, as we are sending a request through Postman the callback URL must be of Postman. Give this URL, https://www.getpostman.com/oauth2/callback, as a callback URL.
In the OAuth scope give it full access and click on save.
As you click on save you will get two more parameters that are used in this process of authentication that is Consumer Key and Consumer Secret. 

Step2: Generate Access token
- Open Postman
- Set Method to Post 
- Set the method URL to https://login.salesforce.com/services/oauth2/token
- In Body define these parameters

grant_type = password
client_id = Consumer Key 

client_secret = Consumer Secret 

username = your Salesforce Account username 

password = password+security_token 

- After applying these steps click on Send button and as a result, an Access token and your instance URL is generated so save it for future reference. 



Step3: Calling custom API using Access Token
- The access token that is generated is used in REST Request to call the web service so to call the service the URL is the same as the URL mapping of Apex-Service for example: “https://instance_name.salesforce.com/services/apexrest/URLMapping”
- Now in the header part provide the access token and content type. 



Authorization: Bearer “your access token” Content-type: application/json

How To Use JSON Class Methods? Useful for parsing Request

// deserialize(jsonString, apexType)

Decimal n = (Decimal)JSON.deserialize('100.1', Decimal.class);



// deserializeStrict(jsonString, apexType)/*

/*

public class Car {

    public String make;

    public String year;

}


// specific Apex Class (a "blueprint") that perfectly matches the incoming JSON.

Car c = (Car)JSON.deserializeStrict(

        '{"make":"SFDC","year":"2020"}',

        Car.class);


// deserializeUntyped(jsonString) // you don't have a blueprint or when the JSON structure is unpredictable (dynamic). String jsonInput = '{\n' + ' "description" :"An appliance",\n' + ' "accessories" : [ "powerCord", ' + '{ "right":"door handle1", ' + '"left":"door handle2" } ],\n' + ' "dimensions" : ' + '{ "height" : 5.5 , ' + '"width" : 3.0 , ' + '"depth" : 2.2 },\n' + ' "type" : null,\n' + ' "inventory" : 2000,\n' + ' "price" : 1023.45,\n' + ' "isShipped" : true,\n' + ' "modelNumber" : "123"\n' + '}'; Map m = (Map) JSON.deserializeUntyped(jsonInput); // serialize(objectToSerialize) Datetime dt = Datetime.newInstance( Date.newInstance( 2011, 3, 22), Time.newInstance( 1, 15, 18, 0)); String str = JSON.serialize(dt);

How To Send The Response In API?

HTTPResponse res = RestContext.response;

res.addHeader('Content-Type', 'text/plain');

res.responseBody = Blob.valueOf('Incorrect Information');

res.statusCode = 400;


SAMAPT......

Comments

Popular posts from this blog

Understanding the Salesforce Approval Process: A Step-by-Step Guide

How to Give Permissions to Automated Process Users or System Context Users

Headless action button using LWC (No Modals)