fbpx

Free Salesforce Developers Tutorials >

Chapter 13 - API >

REST API Part 4

REST API Part 4

What You’ll Learn


S2 Labs

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

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *