0

I am currently working on this app where I make a REST request directly to a table on Salesforce. Currently, it works on Workbench just fine, but I don't understand how to use OAuth with it. I made a connected app, but the "Authentication: Bearer token" does not work. I just need to understand the most simple way to have the basic GET and POST methods via cURL. Thanks. Code is below:

RequestReceiver.apxc

@RestResource(urlMapping='/Product2/*')
global with sharing class RequestReceiver {
    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String prodCode = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Product2 prod = [SELECT Id FROM Product2 WHERE ProductCode = :prodCode];
        delete prod;
    }
    @HttpGet
    global static Product2 doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        RestContext.response.addHeader('Content-Type', 'text/plain');
        String prodCode = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Product2 result = [SELECT Id, Name FROM Product2 WHERE ProductCode = :prodCode];
        return result;
    }
  @HttpPost
    global static String doPost(String name) {
        Product2 prod = new Product2();
        prod.Name = name;
        insert prod;
        return prod.Id;
    }
}

I already have a custom site domain, btw. Thanks.

0

Salesforce authentication and data servers are different. The reason why your rest service works on workbench is because it adds Authorization header automatically.

For your rest service to work:

  1. Use OAuth flow. Here is the link for Salesforce OAuth flow. Salesforce OAuth2.0 or you can find the link by searching "Digging deeper in OAuth" You can use Web server flow or Browser flow.

  2. You will get a session ID, which you can use to make subsequent request to your Rest service.

If you are going to make requests from JavaScript, you may need to add your URL to CORS list.

P. S. I will add more details once I am on my desktop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.