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.
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()); }
- Basic Data Operations (CRUD)
- Powerful Querying and Searching using SOQL and SOSL
- Accessing Metadata
- Specialized Salesforce APIs
- Custom Apex REST Endpoints
Custom Apex REST Endpoints
Use Rest ServiceRestRequest req = RestContext.request;
RestResponse res = RestContext.response;
@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
grant_type = password
client_id = Consumer Keyclient_secret = Consumer Secret
username = your Salesforce Account username
password = password+security_token
Authorization: Bearer “your access token” Content-type: application/json
// 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);
HTTPResponse res = RestContext.response;
res.addHeader('Content-Type', 'text/plain');
res.responseBody = Blob.valueOf('Incorrect Information');
res.statusCode = 400;
Comments
Post a Comment