Experience Salesforce

REST API Part 4

What You’ll Learn

  • Example Of Creating Salesforce Get API
  • How To Use JSON Class Methods?
  • How To Send The Response In API?

Example Of Creating Salesforce Get API

For creating GET API in Salesforce, It is needed to use @HTTPGet above the method definition. It is noted that GET API does not consist of a body, for sending any information data needs to be sent in Params.

Example Code:

@HTTPGet
public static void myMethod() {
       HTTPRequest req = RestContext.request;
       System.debug(req.params);
}

Similarly for other methods, we have @HTTPPut, @HTTPPatch, etc.

How To Use JSON Class Methods?

JSON Class is mostly used in the case of converting JSON-type data into Apex-type data. It consists of various methods which are used to convert jsonString to Apex and Apex to jsonString.

// deserialize(jsonString, apexType)
Decimal n = (Decimal)JSON.deserialize(
               '100.1', Decimal.class);
/*
public class Car {
    public String make;
    public String year;
}
*/
// deserializeStrict(jsonString, apexType)/*
Car c = (Car)JSON.deserializeStrict(
        '{"make":"SFDC","year":"2020"}',
        Car.class);

// deserializeUntyped(jsonString)
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<String, Object> m = 
   (Map<String, Object>)
      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?

The content we receive after calling an API is termed a response.

Here below is the example code to send an API response.

HTTPResponse res = RestContext.response;
res.addHeader('Content-Type', 'text/plain');
res.responseBody = Blob.valueOf('Incorrect Information');
res.statusCode = 400;
salesforce-developer
Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale