Monday, August 26, 2019

Apex REST Code Sample Using RestRequest - Simple as Pie

I always wonder why people are not creating or interacting with Salesforce more using webservices.

If you are..then well done.

The world of possibilities and the layers of integration become infinite.

Always familiarize yourself with utilizing services and definitely create yourself a sandbox.




Apex REST Basic Code Sample

reference : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_sample_basic.htm

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {

    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account account = [SELECT Id FROM Account WHERE Id = :accountId];
        delete account;
    }
  
    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
        return result;
    }
  
  @HttpPost
    global static String doPost(String name,
        String phone, String website) {
        Account account = new Account();
        account.Name = name;
        account.phone = phone;
        account.website = website;
        insert account;
        return account.Id;
    }
}



example : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_sample_restrequest.htm

@RestResource(urlMapping='/MyRestContextExample/*')
global with sharing class MyRestContextExample {

    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
        return result;
    }
  
}


As with the formula post this will be the start of a series where I will post more real life examples.

Stay tuned :-)



No comments:

Post a Comment

Generate reports from Opportunities using a Visualforce Page in Salesforce

  Step 1: Create a Visualforce Page Go to the Setup menu in Salesforce. Search for "Visualforce Pages" in the Quick Find box and c...