Top Solutions for Salesforce REST API Integration

Jennie Lee
6 min readApr 9, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Introduction to Integrating C# .NET and Salesforce’s REST API

Salesforce is a widely used cloud platform that provides various services and functionalities to help businesses manage their customer relationships. One of the key features of Salesforce is its API, which allows developers to integrate Salesforce with other systems and applications.

In a previous series, we explored using Salesforce’s SOAP API to integrate with C# .NET. While the SOAP API is powerful and widely used, Salesforce also provides a REST API that offers a more modern and flexible approach to integration.

In this series, we will focus on integrating C# .NET and Salesforce using the REST API. We will walk through the process of setting up a Connected App in Salesforce, authenticating from .NET, and making API requests using the HttpClient class. By the end of this series, you will have a solid understanding of how to leverage the REST API for seamless integration with Salesforce.

Creating a Connected App in Salesforce

Before we can start integrating with Salesforce’s REST API, we need to create a Connected App in Salesforce. A Connected App is a secure and authenticated entry point into Salesforce for external applications.

To create a new Connected App, follow these step-by-step instructions:

  1. Login to your Salesforce org.
  2. Navigate to the Setup page by clicking on the gear icon in the upper-right corner and selecting “Setup” from the dropdown menu.
  3. In the left-hand sidebar, under the “App Setup” section, click on “Apps” and then select “App Manager”.
  4. Click on the “New Connected App” button.
  5. Specify a name for your Connected App. This can be any name that represents the application you are integrating.
  6. Enter a valid contact email address.
  7. In the “API (Enable OAuth Settings)” section, check the “Enable OAuth Settings” checkbox.
  8. In the “Callback URL” field, enter the URL where Salesforce should redirect the user after authentication. This can be any valid URL, as we will handle the callback programmatically in our .NET application.
  9. Optionally, you can specify the scopes and permissions for your Connected App under the “Selected OAuth Scopes” section.
  10. Click on the “Save” button to create the Connected App.

Once you have created your Connected App, Salesforce will generate a “Consumer Key” and “Consumer Secret” that you will need to authenticate from your .NET application. Make sure to store these values securely, as they provide access to your Salesforce org.

Authenticating from .NET

To authenticate from .NET, we will use the HttpClient class to make HTTP requests to Salesforce’s REST API. HttpClient provides a simple and efficient way to send HTTP requests and receive responses.

Here is an example code snippet that demonstrates how to create the necessary properties for authentication:

var username = "YOUR_SALESFORCE_USERNAME";
var password = "YOUR_SALESFORCE_PASSWORD";
var token = "YOUR_SALESFORCE_SECURITY_TOKEN";
var clientId = "YOUR_CONNECTED_APP_CONSUMER_KEY";
var clientSecret = "YOUR_CONNECTED_APP_CONSUMER_SECRET";

In the code snippet above, replace the placeholder values with your actual Salesforce username, password, security token, client ID, and client secret. The security token is required for authentication from IP ranges that are not trusted by Salesforce.

It’s important to note that storing sensitive information like passwords and security tokens in code is not secure. In a real-world scenario, you would use a secure storage mechanism such as Azure Key Vault or environment variables to store these values.

Using HttpClient for Asynchronous HTTP Callouts

Now that we have the necessary authentication properties, let’s explore how to use HttpClient for asynchronous HTTP callouts to Salesforce’s REST API. Making an asynchronous call allows our application to continue processing other tasks while waiting for the response from the API.

Here is an example code snippet:

using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_AUTHENTICATION_TOKEN");

var response = await httpClient.GetAsync("https://your-salesforce-instance.com/services/data/vXX.X/query/?q=SELECT+Id,Name+FROM+Account");

if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
// Parse the JSON response and handle the data
}
else
{
// Handle the error response
}
}

In the code snippet above, we create a new instance of HttpClient and set the “Authorization” header with the authentication token retrieved from Salesforce’s authentication endpoint. We then make an asynchronous GET request using the GetAsync method and provide the REST API endpoint for querying Accounts. If the response is successful, we read the response content and parse it as JSON.

As you can see, using HttpClient for asynchronous HTTP callouts is straightforward and allows for efficient integration with Salesforce’s REST API.

Sending Requests to Salesforce using FormUrlEncodedContent

When making requests to Salesforce’s REST API, it’s important to send the requests in the proper format. One common approach is to use the FormUrlEncodedContent class to format the request parameters.

Here is an example code snippet:

using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_AUTHENTICATION_TOKEN");

var parameters = new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "client_id", "YOUR_CONNECTED_APP_CONSUMER_KEY" },
{ "client_secret", "YOUR_CONNECTED_APP_CONSUMER_SECRET" },
{ "username", "YOUR_SALESFORCE_USERNAME" },
{ "password", "YOUR_SALESFORCE_PASSWORD" + "YOUR_SALESFORCE_SECURITY_TOKEN" }
};

var content = new FormUrlEncodedContent(parameters);

var response = await httpClient.PostAsync("https://your-salesforce-instance.com/services/oauth2/token", content);

if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
// Parse the authentication response and extract the token and service URL
}
else
{
// Handle the error response
}
}

In the code snippet above, we create a new instance of FormUrlEncodedContent and provide a dictionary of parameters that corresponds to the required fields for authentication. We then make a POST request to the Salesforce authentication endpoint and pass the content as the request body.

Using FormUrlEncodedContent ensures that the requests are properly formatted and increases the chances of a successful integration with Salesforce’s REST API.

Parsing the Authentication Response

Once we have made the HTTP POST request to the Salesforce login endpoint, we need to parse the authentication response and extract the authentication token and service URL.

Here is an example code snippet:

var authenticationResponse = await httpClient.PostAsync(authenticationUrl, content);

if (authenticationResponse.IsSuccessStatusCode)
{
var responseContent = await authenticationResponse.Content.ReadAsStringAsync();
var jsonResponse = JObject.Parse(responseContent);
var authToken = jsonResponse["access_token"].ToString();
var serviceUrl = jsonResponse["instance_url"].ToString();

// Use the authentication token and service URL for subsequent API requests
}
else
{
// Handle the error response
}

In the code snippet above, we read the response content as a string and parse it as JSON using the JObject.Parse method from the Newtonsoft.Json library. We then extract the authentication token and service URL from the JSON response and store them for subsequent API requests.

Parsing the authentication response correctly is crucial for obtaining the necessary information to authenticate and communicate with Salesforce’s REST API effectively.

In the next post of this series, we will use the authentication token to perform a query and retrieve an Account from the Salesforce org.

Conclusion

Integrating C# .NET and Salesforce’s REST API opens up a world of possibilities for seamless and efficient data integration. In this article, we explored the steps for creating a Connected App in Salesforce, authenticating from .NET, and making API requests using the HttpClient class. We also discussed the importance of properly formatting requests and parsing the authentication response.

By following the steps and code snippets provided in this article, you should now have a solid understanding of how to integrate C# .NET and Salesforce’s REST API effectively. With this knowledge, you can build powerful and secure integrations that leverage the capabilities of both platforms.

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--

Jennie Lee
Jennie Lee

Written by Jennie Lee

Software Testing Blogger, #API Testing

No responses yet