Thursday, March 9, 2017

Creating REST APIs using Apex REST

The Salesforce REST API allow you to integration with Salesforce applications using standard HTTP methods such as GET, POST, PUT, PATCH, DELETE, and HEAD. This API provides a way to expose the data you have within your Salesforce application to external applications.

Follow steps to create the Apex REST API. Under App Setup expand Developer and click Apex Classes. Click New to create a new class.

Paste the following code into Apex Class Editor:

@RestResource(urlMapping='/Widgets/*')
global class WidgetController {

    @HttpGet
    global static List<Widget__c> getWidgets() {
        List<Widget__c> widgets = [SELECT Name from Widget__c];
        return widgets;
    }

    @HttpPost 
    global static String createNewWidget(String Name) {
        Widget__c w = new Widget__c();
        w.Name = Name;
        insert w;

        return '{"Status":"Done"}';
   }

    @HttpDelete
    global static String deleteWidgetById() {
        String Id = RestContext.request.params.get('Id');
        String status = RestContext.request.params.get('status');
        List<Widget__c> w = [ Select ID from Widget__c where Id= :Id];

        delete w;

        return '{"Status":"Deleted Widget"}' + status;
    }

    @HttpPut
    global static String updateWidget(String Id, String NewName) {
        Widget__c w = [ Select ID, Name from Widget__c where Id= :Id];

        w.Name = NewName;
        update w;

        return '{"Status":"Widget Updated"}';
    }
}


No comments:

Post a Comment