How can we expose Salesforce data as a REST API? | Salesforce Rest API Controller @HttpGet, @HttpPost, @HttpPut, @HttpPatch or @HttpDelete | How We can expose Salesforce data as a REST API using Apex REST Services.

258 views

Hey guys, today in this post we are going to learn about How can we expose Salesforce data as a REST API? | Salesforce Rest API Controller @HttpGet, @HttpPost, @HttpPut, @HttpPatch or @HttpDelete | How We can expose Salesforce data as a REST API using Apex REST Services in Salesforce.

We can expose Salesforce data as a REST API using Apex REST Services. To do this, we create an Apex class and use the @RestResource annotation to make it accessible from external systems.

Then, we define methods like @HttpGet, @HttpPost, @HttpPut, or @HttpDelete inside that class to perform CRUD operations.

🧩 Key Points to Remember:

1️⃣ Enable API Access

  • Ensure that the Profile or Permission Set of the integration user has API Enabled.
  • Also, the connected app should be configured if you’re using OAuth for authentication.

 

2️⃣ Create an Apex REST Resource Class


  1.  
  2.  @RestResource(urlMapping='/CreateContactAPI/*')
  3.  
  4. global class salesforceRestApiCtrl {
  5.  
  6.     //USING @HttpPost (Correct Way TO INSERT Contact)
  7.     //
  8.  
  9.     @HttpPost
  10.     global static String createContact() {          
  11.  
  12.         RestRequest req = RestContext.request;
  13.         RestResponse res = RestContext.response;
  14.  
  15.         try{
  16.  
  17.            // Parse incoming JSON DATA 
  18.             String requestBody = req.requestBody.toString();
  19.             Map<String, Object> DATA = (Map<String, Object>) JSON.deserializeUntyped(requestBody);
  20.  
  21.             // CREATE NEW Contact record
  22.             Contact con = NEW Contact();
  23.  
  24.                 con.FirstName = (String)DATA.get('FirstName');
  25.                 con.LastName  = (String)DATA.get('LastName');
  26.                 con.Email     = (String)DATA.get('Email');
  27.                 con.Phone     = (String)DATA.get('Phone');
  28.  
  29.             INSERT con;
  30.             //res.statusCode = 201;
  31.             RETURN 'βœ… Contact Created Successfully with Id: ' + con.Id;
  32.  
  33.         }catch(Exception e){
  34.             system.debug('Exception ' + e );
  35.             RETURN '❌ Error: ' + e.getMessage();
  36.         }
  37.  
  38.     }
  39.  
  40.  //Workbench 
  41.  //URL: /services/apexrest/CreateContactAPI/
  42.  //Body:
  43.  /*
  44.    {
  45.      "FirstName": "Vijay",
  46.      "LastName": "Kumar",
  47.      "Email": "vijay.kumar@example.com",
  48.      "Phone": "9876543210"
  49.   }
  50.  
  51.   */ 
  52.  
  53.  
  54.  
  55.      //USING @HttpPost (Correct Way TO GET Contact)
  56.     //
  57.  
  58.  
  59.     @HttpGet
  60.     global static String getContact() {
  61.  
  62.          RestRequest req = RestContext.request;
  63.          RestResponse res = RestContext.response;
  64.  
  65.          system.debug('req ' + req);
  66.          system.debug('res ' + res);
  67.  
  68.         try{
  69.  
  70.             String firstName = req.params.get('firstName');
  71.             String lastName  = req.params.get('lastName');
  72.             String email     = req.params.get('email');
  73.             String phone     = req.params.get('phone');
  74.  
  75.             Contact con = NEW Contact();
  76.  
  77.             con.FirstName = firstName;
  78.             con.LastName  = lastName;
  79.             con.Email     = email;
  80.             con.Phone     = phone;
  81.  
  82.             INSERT con;
  83.  
  84.             RETURN 'βœ… Contact Created Successfully via GET with Id: ' + con.Id;
  85.  
  86.  
  87.         }catch(Exception e){
  88.             //res.statusCode = 400;
  89.             RETURN '❌ Error: ' + e.getMessage();
  90.         }
  91.  
  92.     }
  93.  
  94.  
  95.  
  96.     //How TO Test (IN Browser OR Workbench):
  97.     //
  98.     //GET /services/apexrest/CreateContactGetAPI/?firstName=Vijay&lastName=Kumar&email=vijay.kumar@example.com&phone=9876543210
  99.  
  100.     //
  101.  
  102.  
  103.     // ======================================
  104.     // PUT – FULL UPDATE Contact (REPLACE ALL)
  105.     // ======================================
  106.  
  107.     @HttpPut
  108.     global static String updateContact() {
  109.         RestRequest req = RestContext.request;
  110.         String contactId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
  111.  
  112.         Map<String, Object> reqBody = (Map<String, Object>) JSON.deserializeUntyped(req.requestBody.toString());
  113.  
  114.         Contact con = [SELECT Id, FirstName, LastName, Email, Phone FROM Contact WHERE Id = :contactId LIMIT 1];
  115.  
  116.         con.FirstName = (String)reqBody.get('FirstName');
  117.         con.LastName  = (String)reqBody.get('LastName');
  118.         con.Email     = (String)reqBody.get('Email');
  119.         con.Phone     = (String)reqBody.get('Phone');
  120.  
  121.         UPDATE con;
  122.  
  123.         RETURN 'Contact updated successfully using PUT. Id: ' + con.Id;
  124.     }
  125.  
  126.  
  127.     //Workbench
  128.     ///services/apexrest/CreateContactAPI/003J100000AD3yTIAT
  129.    /* 
  130.     {
  131.       "FirstName": "Amit",
  132.       "LastName": "Verma",
  133.       "Email": "amit@example.com",
  134.       "Phone": "8888888888"
  135.     }
  136.     */
  137.  
  138.  
  139.  
  140.    // πŸ”Ή Partial Contact UPDATE (USE: PATCH)
  141.     @HttpPatch
  142.     global static String patchContact() {
  143.         RestRequest req = RestContext.request;
  144.         String contactId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
  145.  
  146.         Map<String, Object> reqBody = (Map<String, Object>) JSON.deserializeUntyped(req.requestBody.toString());
  147.  
  148.         Contact con = [SELECT Id, FirstName, LastName, Email, Phone FROM Contact WHERE Id = :contactId LIMIT 1];
  149.  
  150.         IF(reqBody.containsKey('Phone')) con.Phone = (String)reqBody.get('Phone');
  151.         IF(reqBody.containsKey('Email')) con.Email = (String)reqBody.get('Email');
  152.  
  153.         UPDATE con;
  154.  
  155.         RETURN 'Contact partially updated using PATCH. Id: ' + con.Id;
  156.     }
  157.  
  158.  
  159.     //Workbench
  160.     ///services/apexrest/CreateContactAPI/003J100000AD3yTIAT
  161.    /* 
  162.     {
  163.       "FirstName": "Amit",
  164.       "LastName": "Verma",
  165.       "Email": "amit@example.com",
  166.       "Phone": "8888888888"
  167.     }
  168.     */
  169.  
  170.  
  171.  
  172.     // πŸ”Ή DELETE Contact Record (USE: DELETE)
  173.     @HttpDelete
  174.     global static String deleteContact() {
  175.         RestRequest req = RestContext.request;
  176.         String contactId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
  177.  
  178.         Contact con = [SELECT Id FROM Contact WHERE Id = :contactId LIMIT 1];
  179.         DELETE con;
  180.  
  181.         RETURN 'Contact deleted successfully. Id: ' + contactId;
  182.     }
  183.  
  184.     //Workbench
  185.     ///services/apexrest/CreateContactAPI/003J100000AD3yTIAT
  186.  
  187.  
  188.  
  189. }

 

Further post that would you like to learn in Salesforce

 

FAQ (Frequently Asked Questions)

Does Salesforce have a REST API?

REST API provides you with programmatic access to your data in Salesforce. The flexibility and scalability of REST API make it an excellent choice for integrating Salesforce into your applications and for performing complex operations on a large scale.

How to enable Salesforce REST API?

Go to Manage Users and click Profiles. Click Edit on the specific profile you're updating. Scroll down to Administrative Permissions and check the API Enabled box. Click Save.

Is Salesforce API free?

Free Salesforce APIs are also available. The primary purpose of these APIs is to help develop new applications and process existing data. Most of these APIs will provide access to basic Salesforce features, such as data, objects, and programmatic access.

πŸ‘‰ Get Complementary β†’

right side banner -- www.w3webmart.com
 
  
πŸ‘‰ Get Free Course β†’

πŸ“Œ Salesforce Administrators

πŸ“Œ Salesforce Lightning Flow Builder

πŸ“Œ Salesforce Record Trigger Flow Builder

πŸ‘‰ Get Free Course β†’

πŸ“Œ Aura Lightning Framework

πŸ“Œ Lightning Web Component (LWC)

πŸ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net