How to use NetSuite REST API with TBA/OAuth 1 and C# .NET

Eric Popivker
ENTech Solutions
Published in
6 min readJan 26, 2023

There are two ways to authorize with NetSuite REST API:

  • Token Based Authentication (TBA — similar to OAuth1)
  • OAuth2

I already wrote about using OAuth 2 to authenticate with NetSuite REST API. That post was here.

In this article, I would like to go back to the OG of NetSuite authentication: TBA. Unlike OAuth2, the TBA never expires, which makes it the best option for connecting to NetSuite API.

The Flavors of TBA Authentication

There are two flavors of TBA authentication:

  • Three-step TBA authorization flow — with user interaction
  • Zero steps TBA authorization flow — manually create token flow

The 3-step flow is your common OAuth1 flow where you obtain Request Token, ask the User to login to authorize access to resources, and exchange Request Token for Access Token (and secret).

The 0-step flow doesn’t require any user interaction. You just create Access Token directly in NetSuite, and you are good to go.

In this article, I will focus on 0-step flow, since it is much more common.

Prerequisites

To use NetSuite REST API, you need to get the following information that can go in the configuration file:

  • AccountId
  • RootApi
  • ClientId (also known as ConsumerKey)
  • ClientSecret (also known as ConsumerSecret)
  • TokenId
  • TokenSecret

Here is how to get this information in NetSuite.

View Company Info

In the NetSuite portal, go to

Setup -> Company -> Company Information

AccountId — is the read-only field “ACCOUNT ID”

RootApi — is in the Company URLs sublist titled “SUITETALK (SOAP AND REST WEB SERVICES)”

Create Integration

In NetSuite, go to Setup -> Integration -> Manage Integrations -> New

You just need TOKEN-BASED AUHENTICATION option checked.

When you save integration and scroll down a bit, you will see ClientId and ClientSecret:

Make sure you save them before leaving the page. But you can always generate new ones by clicking the “Reset Credentials” button (on top).

Create Token

To create an access token, go to:

Setup -> User/Roles -> Access Tokens -> New

APPLICATION NAME: Select integration from the previous step

USER: Select the user that you would like to use for this token.

ROLE: Select a user role with REST permission and permissions to any entities you would like to access in API. You can see all available permissions here.

TOKEN NAME: This will be auto-generated, but you can change it and make it more descriptive.

When you click Save, a new TOKEN ID and TOKEN SECRET will be displayed. You may want to write it down, because you will not be able to see it again in NetSuite UI. But you can always create another token.

Using C#/.NET to call NetSuite REST API

At this time, NetSuite doesn’t provide C# SDK for calling REST API, so you have to get down to the metal.

There are several ways to call NetSuite REST API from .NET

  • RestSharp
  • HttpClient

RestSharp is a bit simpler than HttpClient since it has built-in OAuth1 authorization. HttpClient is the standard way of calling REST in .NET Core, but you have to deal with OAuth1 by yourself.

I created a working example that demonstrates both approaches. You can see all the code on GitHub:

https://github.com/ericpopivker/entech-blog-netsuite-rest-api-tba-demo

The first thing to do is to enter config information from the previous section to NetSuiteApiConfig.cs:

public class NetSuiteApiConfig : IApiConfig
{
public string AccountId { get; } = "<Enter NetSuite AccountID>";

public string ClientId { get; } = "<Enter Integration ClientId>";
public string ClientSecret { get; } = "<Enter Integration ClientSecret>";

public string TokenId { get; } = "<Enter Access TokenId>";
public string TokenSecret { get; } = "<Enter Access TokenSecret>";

public string ApiRoot { get; } = $"https://<Account Prefix>.suitetalk.api.netsuite.com/services/rest/record/v1";

}

The same config will be used for RestSharp and HttpClient. I will describe each approach in detail and reference code in GitHub.

Use RestSharp to call NetSuite REST API

RestSharp includes OAuth1Authenticator class that handles authentication when making calls to NetSuite REST API.

The code for creating RestSharp’s client with OAuth1 is like this:

var client = new RestClient();
var oAuth1 = OAuth1Authenticator.ForAccessToken(
consumerKey: _config.ClientId,
consumerSecret: _config.ClientSecret,
token: _config.TokenId,
tokenSecret: _config.TokenSecret,
OAuthSignatureMethod.HmacSha256);

oAuth1.Realm = _config.AccountId;
client.Authenticator = oAuth1;

It is recommended to use only one instance RestClient since it uses HttpClient internally.

To retrieve one customer you would do something like this:

public async Task<NsCustomer> GetCustomer(int customerId)
{
var url = _config.ApiRoot + "/customer/" + customerId;


var httpRequest = new RestRequest(url, Method.Get);

var httpResponse = await _restClient.ExecuteAsync(httpRequest);
var responseJson = httpResponse.Content;

var customer =
JsonSerializer.Deserialize<NsCustomer>(responseJson);

return customer;
}

NsCustomer is C# DTO that matches partial response from the GetCustomer API call. JSON serialization is done using “System.Text.Json.JsonSerializer”, but you could also leave it up to RestSharp by using code:

var httpResponse = await _restClient.ExecuteAsync<NsCustomer>(httpRequest);
var customer = httpResponse.Data;

The code for ‘GetCustomer’ is simplified for demo purposes, but in real world, you would also need to check httpResponse.IsSuccessful before returning data… Just in case.

Use HttpClient to call NetSuite REST API

HttpClient is included in .NET Core and is a standard way for calling Rest APIs. RestSharp was a much better option in the past because it encapsulated a lot of REST logic, but in recent releases, HttpClient has been catching up. Unfortunately, they still don’t have OAuth1 included.

NetSuite provides good documentation on calling their REST web service using TBA:

https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1534941295.html

So I used the example data they provided to test my OAuth1HeaderGenerator.cs class. The final test looks like this:

  [Test]
public void GetAuthenticationHeaderValueParameter_FromNetSuiteDocExample_Works()
{
//From NetSuite documentation: https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1534941295.html

var oauth1 = CreateOAuth1HeaderGenerator();
var parameter = oauth1.GetAuthenticationHeaderValueParameter(_nonce, _timestamp);

string expected = "realm=\"123456\", oauth_token=\"2b0ce516420110bcbd36b69e99196d1b7f6de3c6234c5afb799b73d87569f5cc\", oauth_consumer_key=\"ef40afdd8abaac111b13825dd5e5e2ddddb44f86d5a0dd6dcf38c20aae6b67e4\", oauth_nonce=\"fjaLirsIcCGVZWzBX0pg\", oauth_timestamp=\"1508242306\", oauth_signature_method=\"HMAC-SHA256\", oauth_version=\"1.0\", oauth_signature=\"B5OIWznZ2YP0OB7VrJrGkYsTh%2B8H%2B5T9Hag%2Bo92q0zY%3D\"";
Assert.AreEqual(expected, parameter);
}

and results match the data in NetSuite API Documentation.

I used OAuth1 spec and NetSuite documentation to write OAuth1HeaderGenerator, so it should be usable for any API that still uses OAuth1.

And finally, to get customer data from REST API, the code looks like this:

public async Task<NsCustomer> GetCustomer(int customerId)
{
var url = _config.ApiRoot + "/customer/" + customerId;

using var httpRequest = CreateHttpRequestMessage(HttpMethod.Get, url);

var httpResponse = await _httpClient.SendAsync(httpRequest);
var responseJson = await httpResponse.Content.ReadAsStringAsync();

var customer =
JsonSerializer.Deserialize<NsCustomer>(responseJson);

return customer;
}

private HttpRequestMessage CreateHttpRequestMessage(HttpMethod httpMethod, string requestUrl)
{
var oauth1 = new OAuth1HeaderGenerator(_config, httpMethod, requestUrl);

var httpRequest = new HttpRequestMessage(httpMethod, requestUrl);
httpRequest.Headers.Authorization = oauth1.CreateAuthenticationHeaderValue();

return httpRequest;
}

Not too shabby.

Conclusion

In this article, we reviewed several ways to call NetSuite REST API from C#/NET Core. RestSharp is pretty straightforward and works out of the box, while HttpClient has some custom OAuth1 logic.

Either approach should work, so pick one depending on your requirements, and happy coding!

GitHub Repo is here:

https://github.com/ericpopivker/entech-blog-netsuite-rest-api-tba-demo

--

--

Eric Popivker
ENTech Solutions

Living in .NET world for 20+ years. Founder of .NET Fiddle.