Monday, December 19, 2022

Apex REST Web services example

Related image

Before discussing REST Web services example, go through my  previous article on Introduction of webservices..


APEX REST Web Services Example

To make your Apex class available as a REST web service is straightforward.

  • Define your class as global,
  • and define methods as global static.
  • Add annotations to the class and methods.

For example, this sample Apex REST class uses one method. The getRecord method is a custom REST API call. It’s annotated with @HttpGet and is invoked for a GET request.

@RestResource(urlMapping=’/Account/*’)
global with sharing class MyRestResource {
@HttpGet
global static Account getRecord() {
// Add your code
}
}

The class is annotated with @RestResource(urlMapping=’/Account/*’).

The base endpoint for Apex REST is https://yourInstance.salesforce.com/services/apexrest/

The URL mapping is appended to the base endpoint to form the endpoint for your REST service. For example, in the class example, the REST endpoint is

https://yourInstance.salesforce.com/services/apexrest/

For your org, it could look something like,

https://yourInstance.salesforce.com/services/apexrest/Account/*

The URL mapping is case-sensitive and can contain a wildcard character (*)

Note: You can use each annotation only once in each Apex class.

Different Types of Annotations available

Annotation Action Details
@HttpGet Read Reads or retrieves records.
@HttpPost Create Creates records.
@HttpDelete Delete Deletes records.
@HttpPut Upsert Typically used to update existing records or create records.
@HttpPatch Update Typically used to update fields in existing records.

Expose a Class as a SOAP Service:

Define your class as global. Add the webservice keyword and the static definition modifier to each method you want to expose. The webservice keyword provides global access to the method it is added to.

The getRecord method is a custom SOAP API call that returns an Account record.

global with sharing class MySOAPWebService

{
webservice static Account getRecord(String id) {
// Add your code
}
}

The external application can call your custom Apex methods as web service operations by consuming the class WSDL file.

Now , Lets try an example:

  1. Open the Developer Console from the Setup gear (Setup gear icon).
  2. In the Developer Console, select File | New | Apex Class.
  3. For the class name, enter AccountManager and then click OK.
  4. Replace the autogenerated code with the following class definition.
@RestResource(urlMapping='/Account/*')
global with sharing class AccountManager {

    @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;
    }
}

Press CTRL+S to save.

Test Your Apex Rest Class in Work Bench (Post example)

  1. Navigate to https://workbench.developerforce.com/login.php.
  2. For Environment, select Production.
  3. Select the latest API version from the API Version drop-down.
  4. Accept the terms of service, and click Login with Salesforce.
  5. To allow Workbench to access your information, click Allow.
  6. Enter your login credentials and then click Log in to Salesforce.
  7. After logging in, select utilities | REST Explorer.
  8. Select POST.
  9. The URL path that REST Explorer accepts is relative to the instance URL of your org. Provide only the path that is appended to the instance URL. In the relative URI input field, replace the default URI with/services/apexrest/Cases/.
  10. For the request body, insert the following JSON string representation of the object to insert.

{
“Name” : “MK”,
“Phone” : “8867”

}

11. Click Execute.

This invocation calls the method that is associated with the POST HTTP method, namely the doPost method.
  1. To view the response returned, click Show Raw Response.
    The returned response looks similar to this response. The response contains the ID of the new Account record.

Same way you can write examples for Get, Put, Patch ,Delete….

Another Sample Example:


@RestResource(urlMapping='/v1/AccountMgmt/')
global class AccountMgmt{
    @httpGet
    global static Account doGetMethod(){
    Account acc= new Account();
    Map<String,String> paramsMap = RestContext.request.params;
    String accid=paramsMap.get('id');
    acc = [select id,name,AnnualRevenue from Account where Id =:accid];
    return acc;
    }
 
    @httpDelete
    global static String doDeleteMethod(){
    Account acc= new Account();
    Map<String,String> paramsMap = RestContext.request.params;
    String accid=paramsMap.get('id');
    acc = [select id,name,AnnualRevenue from Account where Id =:accid];
    delete acc;
    return 'You have deleted the record succesfully!';
    }
 
   @httpPost
    global static Account doPostMethod(String Name, Integer AnnualRevenue){
    Account acc= new Account(Name =name,AnnualRevenue = annualrevenue);
    insert acc;
    return acc;
    }
   @httpPut
    global static Account doPutMethod(String Name, Integer AnnualRevenue){
    Map<String,String> paramsMap = RestContext.request.params;
    String accid=paramsMap.get('id');
     Account acc= new Account(Name =name, AnnualRevenue = annualrevenue, Id =accid);
    update acc;
    return acc;
    }
}

And you can use work bench as external webservice.

Get Method Screenshot:

Delete Method Screenshot:

Post Method Screenshot:

Put Method Screenshot:

Thanks for Reading..

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...