Your first REST API requests with Node.js

Get started quickly with the Sage Intacct REST API. This tutorial will show you how to use Node.js to authenticate with OAuth2 server, send requests to the API, and review the responses.


Prerequisites

  • You must have an active Web Services developer license, which includes a Web Services sender ID and password. If you need a developer license, contact your account manager.
  • The company to which you will be sending API requests must authorize your sender ID. They can either add your web sender ID to the Company Security tab or log in as an admin user when approving the OAuth authorization request.
  • There must be an Intacct user with the permissions required by your application. It is strongly recommended that you use a Web Services user.
  • You must register your application with the Sage App Registry and obtain a Client ID and Client Secret . You must provide a redirect (callback) URI where the user will be redirected once authorized. See the Quick start topic for more details.
  • Node.js >= 12.18.0
  • Server with SSL

Set up

  1. Download the Node.js REST API example:
  2. Create a new Node.js project for the examples in your IDE of choice (WebStorm, Visual Studio, etc.).
  3. Make sure your server is running.
  4. Deploy the project into your web server root directory.

Overview of authentication flow

Your application must be authorized by a user in order to get an access token. The access token must be included in every API request. The OAuth2 authorization code flow involves the following steps:

  1. The user clicks a link to authorize your application.
  2. The user signs in to Intacct and grants access to their data.
  3. The authentication server responds by issuing an authorization code and redirecting the user to the registered callback URI.
  4. Capture the authorization code and use it to request an access token.
  5. Receive and capture the access token which can now be used to send requests to the REST API.

Overview of implementation

This tutorial uses two HTML files with JavaScript that you will host on your server. The first file REST_auth.html lets a user initiate an authorization request. The second file REST-example-token.html receives the authorization code and requests an access token, then sends an API request. REST-example-token.html file is the redirect (callback) URI which must be entered in your Sage App registry as mentioned in the Prerequisites section above.

The tutorial uses the JavaScript fetch() method and async/await syntax to send HTTP GET and POST requests to the API.


Obtain the access token

Store your credentials

Open the credentials-template.js file and enter your client id and client secret. Enter you callback (redirect URI) replacing "mysite.com" with your host domain. Verify the callback URI is correctly entered in the Sage App Registry.

Copy
Copied
const "CLIENT_ID" = "*****.app.sage.com"
const "CLIENT_SECRET" = "*****"
const "CALLBACK_URL" = "https://mysite.com/CallbackAndRestCalls/REST-example-token.html"

Save the file as credentials.js in your root directory. Store your file securely and exclude it from your remote repository.

Send authorization request

With the server running, the IntacctRestAuth/REST_auth.html file displays a link to the authorization endpoint that a user can click to authorize your application.

  • Endpoint: https: //api.intacct.com/ia/api/v1/oauth2/authorize
  • HTTP method: GET
  • Fields:
    • response_type: code
    • client_id:
    • redirect_uri:
    • state: a random value used to validate the response

Example request:

Copy
Copied
https://api.intacct.com/ia/api/v1/oauth2/authorize?response_type=code&client_id=b5974b6c5d6f2f1edb33.app.sage.com&redirect_uri=https://mysite.com/rest-callback.html&state=123456

Open the IntacctRestAuth/REST_auth.html file and examine the JavaScript code to send the request.

Copy
Copied
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>JavaScript REST authorization example</title>
    <script src="../credentials.js"></script>
    <script>
        const base_url = 'https://api.intacct.com/ia/api/'
        const version = 'v1/'
        const auth_endpoint = 'oauth2/authorize'
    </script>
</head>
<body>
<script>
    // build endpoint
    auth_url = base_url + version + auth_endpoint

    myurl = auth_url + "?"
        + "state=123456"
        + "&response_type=code"
        + "&client_id=" + CLIENT_ID
        + "&redirect_uri=" + CALLBACK_URL

    document.write('<a href="' + myurl + '">Authorize application</a>')

</script>
</body>
</html>

Open the file in your browser and click the Authorize access link to start the authorization process. The OAuth2 server responds by opening the Sage Intacct log in page.

Log in as a user with the permissions needed by your application and authorize the application to access data.

The OAuth2 server responds by redirecting the user to the registered redirect URI and including an authorization code as a query parameter in the URL.

Send access token request

Extract the authorization code from the response, then include it in a request for the access token.

  • Endpoint: https: //api.intacct.com/ia/api/v1/oauth2/token
  • HTTP method: POST
  • Fields:
    • grant type: authorization code
    • code: < code >
    • client_id
    • client_secret
    • redirect_uri
    • content_type: application/json

Open the CallbackAndRestCalls/REST-example-token.html file and examine the JavaScript code to send the request.

In the <head> section, include the credentials.js file and configure the endpoint.

Copy
Copied
<head>
    <meta charset="UTF-8"/>
    <title>JavaScript REST authorization example</title>
    <script src="../credentials.js"></script>
    <script>
        const base_url = 'https://api.intacct.com/ia/api/'
        const version = 'v1/'
        const token_endpoint = 'oauth2/token'
    </script>
</head>

Extract the authorization code from the response URL and begin authorization by invoking the authorize() function.

Copy
Copied
const code = new URLSearchParams(window.location.search).get('code')
authorize(code)

The async authorize() function returns a promise. When the await keyword is used, execution will pause until the server responds and the promise is settled, then returns its result.

Copy
Copied
async function authorize(code) {

    // build endpoint
    let token_url = base_url + version + token_endpoint

    // build authentication request
    const inputBody = new URLSearchParams();
    inputBody.append('grant_type', 'authorization_code');
    inputBody.append('code', code);
    inputBody.append('redirect_uri', CALLBACK_URL);
    inputBody.append('client_id', CLIENT_ID);
    inputBody.append('client_secret', CLIENT_SECRET);
    inputBody.append('Content-Type', 'application/json');

    // send request to authenticate
    myresponse = await fetch(token_url,
        {
            method: 'POST',
            body: inputBody
        })

The response contains the access token in JSON format.

Copy
Copied
    // wait for response, then extract access token
    if (myresponse.ok) {
        let responseBody = await myresponse.json();
        token = new URLSearchParams(responseBody).get('access_token')
    } else console.error('Error:', error)

Send an API request

With the access token in hand, you can now use it to send API requests to access data on behalf of the authorizing user. As an example, you can query for vendor object with key 33.

  • Endpoint: https: //api.intacct.com/ia/api/v1/objects/accounts-payable/vendor/33
  • HTTP method: GET
  • Header:
    • Authorization: Bearer < access token >

Examine the JavaScript code to send the request:

Copy
Copied
//query for vendor key 33 in my company

// build endpoint
const request_url = base_url + version + 'objects/accounts-payable/vendor/33'

const requestHeaders = {
        'Authorization': 'Bearer ' + token
}

myresponse = await fetch(request_url,
    {
        method: 'GET',
        headers: requestHeaders
    })

The response contains the requested vendor information in JSON format.

Copy
Copied
// wait for response, then extract vendor data
if (myresponse.ok) {
    let responseResult = await myresponse.json();
    with (responseResult['ia::result']) {
        document.write("Vendor key: " + key + "<br />")
        document.write("Vendor id: " + id + "<br />")
        document.write("Vendor name: " + name + "<br />")
    }
} else console.error('Error:', error)

Examine the response. You will see the key, id and name information for vendor with key 33.

Copy
Copied
Vendor key: 33
Vendor id: V-00019
Vendor name: Bay Area Exhibits, Inc

Use the access token to send API requests in subsequent tutorials. Sample token is shown here:

Copy
Copied
Access token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJZCI6ImI1OTc0YjZjNWQ2ZjJmMWVkYjg0LmFwcC5zYWdlLmNvbSIsImNueUlkIjoiU3RldmUgRXZlcnl0aGluZyIsImNueUtleSI6IjQ0MTEyMTI5IiwidXNlcklkIjoic3RldmUubmF5IiwidXNlcktleSI6IjY4Iiwic2Vzc2lvbklkIjoiemVvYlFNRHBfRnk3SFFJUENIUmVRLWhQWExrZEFzM3FHMERDU09GZHV4MENEd2gwWGdkZTZWeTcifQ.giY62IE-wRtN6xuM3EBI-RaHEu4HJzZKpmSnYu2uRCo