Skip to main content

RestFul API in Salesforce Create & Consume both

 Restful API in Salesforce Create & Consume both


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

global with sharing class RestAPIService {

    @HttpGet

    global static String doGet() {

        List<countryies__c> obj = [Select ID,Name from countryies__c];

        String data='';

        for(countryies__c item:obj)

        {

            data += 'ID is '+ item.id + 'Name is ' + item.Name + '\n';

        }

        return data;

    }

    @HttpPost

    global static String doPost(String name) {

       countryies__c obj = new countryies__c();

        obj.Name=name;

        insert obj;

        

        return 'Country ' + name + ' Added';

    }

    @HttpPut

    global static String putAPI(String oname,String name) {

          countryies__c obj = [Select ID,Name from countryies__c where Name=:oname limit 1];

          obj.Name=name;

          update obj;

        return 'Hello PUT API EXAMPLE';

    }

    

    @HttpDelete

    global static String deleteAPI() {

         RestRequest req = RestContext.request;

        RestResponse res = RestContext.response;


        Id r = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

        countryies__c obj = [Select ID,Name from countryies__c where Id=:r limit 1];

        delete obj;

        return 'Hello Delete' + r;

    }

    

}


Consume Rest Services under APEX :


public with sharing class ConsumeAPI {

    @AuraEnabled

    public static String testGetAPI() {

        Http http = new Http();

        HttpRequest request = new HttpRequest();


        // Dynamic org base URL

        String baseUrl = URL.getOrgDomainUrl().toExternalForm();

        String endpoint = baseUrl + '/services/apexrest/MyService';

      


        request.setEndpoint(endpoint);//url

        request.setMethod('GET');


        // Add session header

        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());


        request.setTimeout(60000);


        HttpResponse response = http.send(request);


        System.debug('👉 Status Code: ' + response.getStatusCode());

        System.debug('👉 Response Body: ' + response.getBody());


        if (response.getStatusCode() == 200) {

            return response.getBody();

        } else {

            return '{"error": "API call failed with status ' + response.getStatusCode() +

                   ', message: ' + response.getBody() + '"}';

        }

    }


 @AuraEnabled

    public static String testPOSTAPI(String name) {

        Http http = new Http();

        HttpRequest request = new HttpRequest();


        // Dynamic org base URL

        String baseUrl = URL.getOrgDomainUrl().toExternalForm();

        String endpoint = baseUrl + '/services/apexrest/MyService';

      


        request.setEndpoint(endpoint);//url

        request.setMethod('POST');

        request.setHeader('Content-Type', 'application/json');

        // Add session header

        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

        String jsonBody = '{"name":"'+name+ '"}'; 

        request.setBody(jsonBody);


        request.setTimeout(60000);

        

        HttpResponse response = http.send(request);


        System.debug('👉 Status Code: ' + response.getStatusCode());

        System.debug('👉 Response Body: ' + response.getBody());


        if (response.getStatusCode() == 200) {

            return response.getBody();

        } else {

            return '{"error": "API call failed with status ' + response.getStatusCode() +

                   ', message: ' + response.getBody() + '"}';

        }

    }


    @AuraEnabled

    public static String testPUTAPI(String oname,String name) {

        Http http = new Http();

        HttpRequest request = new HttpRequest();


        // Dynamic org base URL

        String baseUrl = URL.getOrgDomainUrl().toExternalForm();

        String endpoint = baseUrl + '/services/apexrest/MyService';

      


        request.setEndpoint(endpoint);//url

        request.setMethod('PUT');

        request.setHeader('Content-Type', 'application/json');

        // Add session header

        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

        String jsonBody = '{"oname":"'+ oname +'","name":"'+ name +'"}';

        request.setBody(jsonBody);


        request.setTimeout(60000);

        

        HttpResponse response = http.send(request);


        System.debug('👉 Status Code: ' + response.getStatusCode());

        System.debug('👉 Response Body: ' + response.getBody());


        if (response.getStatusCode() == 200) {

            return response.getBody();

        } else {

            return '{"error": "API call failed with status ' + response.getStatusCode() +

                   ', message: ' + response.getBody() + '"}';

        }

    }

 @AuraEnabled

    public static String testDELETEAPI() {

        Http http = new Http();

        HttpRequest request = new HttpRequest();


        // Dynamic org base URL

        String baseUrl = URL.getOrgDomainUrl().toExternalForm();

        String endpoint = baseUrl + '/services/apexrest/MyService/a0ZdM000003RnCbUAK';

      


        request.setEndpoint(endpoint);//url

        request.setMethod('DELETE');

        request.setHeader('Content-Type', 'application/json');

        // Add session header

        request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

       

        


        request.setTimeout(60000);

        

        HttpResponse response = http.send(request);


        System.debug('👉 Status Code: ' + response.getStatusCode());

        System.debug('👉 Response Body: ' + response.getBody());


        if (response.getStatusCode() == 200) {

            return response.getBody();

        } else {

            return '{"error": "API call failed with status ' + response.getStatusCode() +

                   ', message: ' + response.getBody() + '"}';

        }

    }


public static void postDataIntoAPI(String name,String email,String gender,String status) {

     try

     {

       Http http = new Http();

HttpRequest request = new HttpRequest();

request.setEndpoint('https://gorest.co.in/public/v2/users');

request.setMethod('POST');


// Headers

request.setHeader('Content-Type', 'application/json');

request.setHeader('Authorization', 'Bearer c1c7fa5775f13f847f27051131afb2621a0cb317ee666d28e3e88d22defcc5b8');


// Proper JSON body

String jsonBody = '{"name":"'+name+'","email":"'+email+'","gender":"'+gender+'","status":"'+status+'"}';

request.setBody(jsonBody);


// Send request

HttpResponse response = http.send(request);


System.debug('Status: ' + response.getStatus());

System.debug('Body: ' + response.getBody());


        

     }

     catch(Exception ex)

     {

         

     }

 }

 public static void putDataIntoAPI(integer id,integer uid,String title,String body) {

     try

     {

         Http http = new Http();

         HttpRequest request = new HttpRequest();

         request.setEndpoint('https://jsonplaceholder.typicode.com/posts/'+id);

         request.setMethod('PUT');

         request.setHeader('Content-Type', 'application/json');

         request.setBody('{"title":"'+title+'","body":"'+body+'","userId":'+uid+'}');

         HttpResponse response = http.send(request);

         System.debug('Status: ' + response.getStatus());

         System.debug('Body: ' + response.getBody());

        

     }

     catch(Exception ex)

     {

         

     }

 }

    public static void deleteDataIntoAPI(integer id) {

     try

     {

         Http http = new Http();

         HttpRequest request = new HttpRequest();

         request.setEndpoint('https://jsonplaceholder.typicode.com/posts/'+id);

         request.setMethod('DELETE');

         request.setHeader('Content-Type', 'application/json');

         HttpResponse response = http.send(request);

         System.debug('Status: ' + response.getStatus());

         System.debug('Body: ' + response.getBody());

        

     }

     catch(Exception ex)

     {

         

     }

 }

 @AuraEnabled

 public static String getUsersFromAPI() {

         Http http = new Http();

         HttpRequest request = new HttpRequest();

         request.setEndpoint('https://jsonplaceholder.typicode.com/users');

        // request.setEndpoint('callout:JSONPLACEHODLER');

         request.setMethod('GET');

         HttpResponse response = http.send(request);

         if(response.getStatusCode() == 200) {

             return response.getBody();

           /*  List<Object> users = (List<Object>) JSON.deserializeUntyped(response.getBody());

             for(Object obj : users) {

                    Map<String, Object> user = (Map<String, Object>) obj;

                    System.debug('Name: ' + user.get('name'));

                    System.debug('Email: ' + user.get('email'));

                }*/

         }

     else {

                return '{"error": "API call failed with status ' + response.getStatusCode() + '"}';

            }

     

 }

}


Consume RestAPI under outside of salesforce under postman


1)  Login into postman.com

2) create workspace

3) search Salesforce Platform API

4)  enable CORS setting in salesforce with postman.com & postman.co

5)  Salesforce Platform API Auth 2.0 click on it

6) Click on AUTH and go into bottom and click on GET NEW ACCESS TOKEN Button

7) Authorize then it provide use token click on it

8)  copy url and set into endpoint under variable section

9) go into RestAPI and call your url like this way

{{_endpoint}}/services/apexrest/MyService


Without Endpoint variable

https://shivaconceptsolution-dev-ed.develop.my.salesforce.com/services/apexrest/MyService/a0ZdM000003RnCbUAK

Comments

Popular posts from this blog

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

Conditional Statement in Python

It is used to solve condition-based problems using if and else block-level statement. it provides a separate block for  if statement, else statement, and elif statement . elif statement is similar to elseif statement of C, C++ and Java languages. Type of Conditional Statement:- 1) Simple if:- We can write a single if statement also in python, it will execute when the condition is true. for example, One real-world problem is here?? we want to display the salary of employees when the salary will be above 10000 otherwise not displayed. Syntax:- if(condition):    statements The solution to the above problem sal = int(input("Enter salary")) if sal>10000:     print("Salary is "+str(sal)) Q)  WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed. Solution:- x = int(input("enter salary")) if x<10000:     x=x+500 print(x)   Q) WAP to display th...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...