function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Benjamin RushBenjamin Rush 

How can you call REST web services written in Salesforce from an external website using AJAX?

I am wanting to set up REST web services inside of Salesforce that can get, create, and change records for a particular object (leads in this case) whenever it is invoked. I will be invoking these methods from an external website. The POST (create) method I will be using is shown below. I will obviously be adding functionality to the web services themselves. I am only looking to figure out how to actually call them rather than how to write them.
@RestResource(urlMapping='/lead/*')
global class MyWebService {
    @HttpPost
    global static id postLead(string firstName, string lastName, string leadSource, string status) {
        lead newLead = new Lead();
        newLead.FirstName = firstName;
        newLead.LastName = lastName;
        newLead.LeadSource = leadSource;
        newLead.Status = status;
        insert newLead;
        return newLead.id;
}
Then in my javascript (jQuery allowed) code on the external site, I would presumably be creating HttpRequest objects that call these methods; however, I can't seem to get anywhere on this topic. I've tested a plethora of different parameters, but my general code is along the lines of
$.ajax(
    method:"get",
    cache:false,
url:"https://myinstance.lightning.force.com/services/apexrest/lead/leadIdHere",
    success: function(data) {
       alert(data);
    }
);
I know that this is in part because you need to authenticate, but I can'r seem to figure out what the URI for that method would be, not how to retain it. I've tried going through this with JSForce (https://jsforce.github.io) but haven't had any luck there (although I was able to get login authentication working with that.

I am just looking to call a simple REST web service that has been written inside of Salesforce from an external webpage using JavaScript.
 
Benjamin RushBenjamin Rush
As a side note: while using workbench's utilities > REST explorer and setting the appropriate values everything is working great, so that means the issue almost certainly in dealing with the actual call to the web services as well as the authentication beforehand.
DimondDimond
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_what_is_rest_api.htm
Benjamin RushBenjamin Rush
Thanks for the timely response and documentation Dimond! Over the 50 or so articles I've gone through, I hadn't hit this particular one so I will definitely go through this and respond back with any solutions if I can reach them.