In this article we’ll look at calling a custom Salesforce REST endpoint using C#.

In order to accomplish this you will need the following –

  • Visual Studio 2012+
  • At least a developer instance of Salesforce
  • Administrator rights in Salesforce for adding apps and creating Apex

The first thing you should do is create the actual endpoint using Salesforce Apex. Log into your instance and open the Developer Console.

Create a new Apex class with the following code –

@RestResource(urlMapping='/CreateAccountContactCombo/*')
global class CreateAccountContactCombo
{
    @HttpPost
    global static string doPost(string accountName, string firstName, string lastName)
    {
        Account acc = new Account();
        acc.Name = accountName;
        insert acc;
        Contact con = new Contact();
        con.FirstName = firstName;
        con.LastName = lastName;
        con.AccountId = acc.Id;
        insert con;
        return 'AccountId:' + acc.Id + ' - ContactId:' + con.Id;
    }
}

This sample code creates an account with one sub-contact and returns the ids of the newly created records.

In order to actually call this from an external source you’ll need to enable OAuth in Salesforce by creating a Connected App. Follow these steps – https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm

Now that authentication is enabled you need to determine the following values –

  • User Name
  • Password
  • Security Token
  • Client Id
  • Client Secret

User Name and Password should be self-explanatory (user must be able to call APIs and Apex). The quickest way to get the Client Id and Secret is to look at the Connected App by going to Salesforce-> Setup-> Create -> Apps. Your security token is e-mailed to you when you’re added to Salesforce but you can always get a new one by performing a Password Reset.

Now that all the required authentication values have been determined you can start building a simple application to test the call. Open Visual Studio and create a new C# Console Application (.NET 4.5.2+).

In order for this sample to work you will need to add a reference to the Force.com Toolkit for .NET which you can find here – https://github.com/developerforce/Force.com-Toolkit-for-NET

You will also need to add a reference to Json.NET which you can find here – http://www.newtonsoft.com/json

These assemblies are also available as Nuget Packages under the names DeveloperForce.Force and Json.NET.

Now that you have added the proper references to your project, copy and paste the following code which will be used to call the custom REST endpoint –

using Newtonsoft.Json;
using Salesforce.Common;
using Salesforce.Force;
using System;
using System.Threading.Tasks;namespace SFAPITester
{
class SFAPITest
{
// TODO: Replace these constants with your own authentication values
private const string USER_NAME = “[USER_NAME]”;
private const string PASSWORD = “[PASSWORD]”;
private const string SECURITY_TOKEN = “[SECURITY_TOKEN]”;
private const string CLIENT_ID = “[CLIENT_ID]”;
private const string CLIENT_SECRET = “[CLIENT_SECRET]”;private const string AUTH_URL = “https://login.salesforce.com/services/oauth2/token”;
private const string SANDBOX_AUTH_URL = “https://test.salesforce.com/services/oauth2/token”;// TODO: Switch this to true if you are running in a Sandbox environment
private const bool USE_SANDBOX = false;private static AuthenticationClient _auth;
private static ForceClient _client;static void Main(string[] args)
{
string authUrl = USE_SANDBOX ? SANDBOX_AUTH_URL : AUTH_URL;// Connect to SF
_auth = new AuthenticationClient();
_auth.UsernamePasswordAsync(CLIENT_ID, CLIENT_SECRET, USER_NAME, PASSWORD + SECURITY_TOKEN, authUrl).Wait();_client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion);

// Call Custom REST and wait for the response
Task<string> result = CallCustomRESTEndpoint();
result.Wait();

// Show the Ids of the created Account and Contact
Console.WriteLine(result.Result);

Console.Read();
}

public static async Task<string> CallCustomRESTEndpoint()
{
// JSON body where the property names match the parameter names in the SF API signature
string body = “{”accountName”:”TestAccountName”,”firstName”:”TestFirstName”,”lastName”:”TestLastName”}”;

object bodyObject = JsonConvert.DeserializeObject(body);

var returnValue = await _client.ExecuteRestApiAsync<string>(“CreateAccountContactCombo”, bodyObject);

return returnValue;
}
}
}

Set the constant values used for authentication such as USER_NAME, PASSWORD, etc to your own values. Also, make sure to set the USE_SANDBOX variable to true if you are running this code against a Salesforce Sandbox as the authorization URL is different.

Now run the application and it should create an account and contact in Salesforce. The ids should be outputted to the console window.

While this was only a quick sample, you now have a working connection which you can use to build out more complex calls.

For more information on creating custom REST APIs in Salesforce refer to the following link – https://developer.salesforce.com/page/Creating_REST_APIs_using_Apex_REST