• Stars
    star
    177
  • Rank 215,985 (Top 5 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Javascript interface for interacting with the Box API. You can find the node package at

“box-dev-logo”

Box Node.js SDK

Known Vulnerabilities Platform Project Status Coverage

A Node.js interface to the Box Content API.

Installation

Node SDK Installation details.

npm install --save box-node-sdk

Getting Started

To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account.

var BoxSDK = require('box-node-sdk');

// Initialize the SDK with your app credentials
var sdk = new BoxSDK({
  clientID: 'CLIENT_ID',
  clientSecret: 'CLIENT_SECRET'
});

// Create a basic API client, which does not automatically refresh the access token
var client = sdk.getBasicClient('DEVELOPER_TOKEN');

// Get your own user object from the Box API
// All client methods return a promise that resolves to the results of the API call,
// or rejects when an error occurs
client.users.get(client.CURRENT_USER_ID)
	.then(user => console.log('Hello', user.name, '!'))
	.catch(err => console.log('Got an error!', err));

Creating API Clients

Clients are used to communicate with the API on behalf of a user.

Box supports three different types of client:

  • Basic Client: Simple, makes calls via the given access token until the access token expires
  • Persistent Client: For use with traditional OAuth2 apps, can refresh its tokens automatically and persist them via a token store
  • App Auth Client: Uses the app auth JWT grant to act on behalf of app/managed users and create new tokens automatically

Basic Client

Returns a Box Client with a Basic API Session. The client is able to make requests on behalf of a user. A basic session has no access to a user's refresh token. Because of this, once the session's tokens expire the client cannot recover and a new session will need to be generated.

var client = BoxSDK.getBasicClient('ACCESS_TOKEN');

Persistent Client

Returns a Box Client with a persistent API session. A persistent API session helps manage the user's tokens, and can refresh them automatically if the access token expires. If a central data-store is given, the session can read & write tokens to it.

NOTE: If tokenInfo or tokenStore are formatted incorrectly, this method will throw an error. If you haven't explicitly created either of these objects or are otherwise not completely confident in their validity, you should wrap your call to getPersistentClient in a try-catch to handle any potential errors.

If you do not provide a token store object, the SDK will continue refreshing tokens locally as long as the Node.js process lives, but will not able to restore the user's authentication on process restart or share that authentication state between different processes.

var client = sdk.getPersistentClient(tokenInfo, null);

Providing a token store will allow the SDK to persist the user's authentication state so that you can resume making API calls as a user if the Node.js process needs to restart, or share the authentication state between multiple different processes.

var client = sdk.getPersistentClient(tokenInfo, tokenStore);

The token store is the interface used by persistent clients to interact with the consumer app's central storage layer. For a token store to be valid, it must have the following three methods:

store.read(function(err, data) {}); // read TokenInfo from app central store.
store.write(tokenInfo, function(err, data) {}); // write TokenInfo to the app's central store.
store.clear(function(err, data) {}); // delete TokenInfo from the app's central store.

Note that these methods don't pass in identifying information as arguments. You'll most likely need to create them on-demand for each client.

App Auth Client

App Auth allows an app to fully manage the Box accounts of its users; they do not have direct login credentials to Box and all operations are performed through the API using a JWT grant.

If you have a JSON configuration file from the Box Developer Console that includes your private key information, you can import that directly to create an SDK instance:

var sdkConfig = require('/path/to/config.json');
var sdk = BoxSDK.getPreconfiguredInstance(sdkConfig);

// Get the service account client, used to create and manage app user accounts
// The enterprise ID is pre-populated by the JSON configuration,
// so you don't need to specify it here
var serviceAccountClient = sdk.getAppAuthClient('enterprise');

// Get an app user or managed user client
var appUserClient = sdk.getAppAuthClient('user', 'YOUR-APP-USER-ID');

Otherwise, you can manually pass the necessary configuration parameters to the SDK:

var sdk = new BoxSDK({
	clientID: 'CLIENT_ID',
	clientSecret: 'CLIENT_SECRET',
	appAuth: {
		keyID: 'PUBLIC_KEY_ID',
		privateKey: 'PRIVATE_KEY',
		passphrase: 'PRIVATE_KEY_PASSPHRASE'
	}
});

// Get the service account client, used to create and manage app user accounts
var serviceAccountClient = sdk.getAppAuthClient('enterprise', 'APP_ENTERPRISE_ID');

// Get an app user or managed user client
var appUserClient = sdk.getAppAuthClient('user', 'YOUR-APP-USER-ID');

Using the Client to Make API Calls

The different API endpoints you can call are represented as methods, grouped into managers by the type of object they interact with.

For example:

// Get the user object for the current user
client.users.get(client.CURRENT_USER_ID)
	.then(currentUser => { /* ... */ })
	.catch(error => { /* handle any errors */ });

// Update the name for folder with ID 123
client.folders.update('123', { name: 'New Folder Name' })
	.then(folderInfo => { /* ... */ })
	.catch(error => { /* handle any errors */ });

// Upload a new file to folder 123
client.files.uploadFile('123', 'bicycle.png', fileContents)
	.then(fileObject => { /* ... */ })
	.catch(error => { /* handle any errors */ });

// Delete the comment with ID 456
client.comments.delete('456')
	.then(() => { /* ... */ })
	.catch(error => { /* handle any errors */ });

For complete documentation about the available operations, please see the SDK documentation pages and the auto-generated JSDocs. These contain detailed information about which methods are available and how to use them.

Constructing API Calls Manually

The SDK also exposes low-level request methods for constructing your own API calls. These can be useful for adding your own API calls that aren't yet explicitly supported by the SDK.

The low-level methods always return a response object that contains the raw API response, and do not turn non-2xx status codes into errors like the normal client methods do.

// GET /files/123?fields=id,name
client.get('/files/123', {qs: {fields: 'id,name'}})
	.then(response => { /* ... */ })
	.catch(error => { /* handle any errors */ });

// PUT /files/123
// {
//     "name": "New File Name"
// }
client.put('/files/123', {body: {name: 'New File Name'}});
	.then(response => { /* ... */ })
	.catch(error => { /* handle any errors */ });

// DELETE /files/123
client.del('/files/123');
	.then(response => { /* ... */ })
	.catch(error => { /* handle any errors */ });

FIPS 140-2 Compliance

The Box Node SDK allows the use of FIPS 140-2 validated SSL libraries, such as OpenSSL 3.0. However, some actions are required to enable this functionality.

By default, the version of OpenSSL Node.js includes is not FIPS enabled. Therefore, if you want to use OpenSSL 3.0 with FIPS, you need to build OpenSSL 3.0 with FIPS enabled and then build Node.js use the shared OpenSSL 3.0 library.

According to Node.js OpenSSL Strategy document, you can use the OpenSSL 3.0 from Node.js v16 or later.

Versions

We use a modified version of Semantic Versioning for all changes. See version strategy for details which is effective from 30 July 2022.

Supported Version

Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version.

A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features.
Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date.

Version schedule

Version Supported Environments State First Release EOL/Terminated
3 Node.js >= 14 and <= 20 Supported 23 May 2023 TBD
2 Node.js >= 8 and <= 14 Maintained 29 Sep 2021 23 Jul 2023
1 EOL 28 Mar 2019 29 Sep 2021

Questions, Bugs, and Feature Requests?

Browse the issues tickets! Or, if that doesn't work, file a new one and someone will get back to you. If you have general questions about the Box API, you can post to the Box Developer Forum.

Contributing to the Box Node.js SDK

  1. Clone this repo.
  2. Run npm install.
  3. Run npm test to ensure everything is working.
  4. Make the changes you want in the lib/ directory. Be sure to add corresponding tests in the tests/ directory!
  5. Run the unit tests by command npm run test and integration test as instructed here.
  6. Create a pull request with your changes — we'll review it and help you get it merged.

Currently, the Sign Request module is generated automatically from OpenAPI specs. To re-generate this module, download the latest version of Box OpenAPI specs here, save it to the root directory and run npm run codegen.

For more information, please see the Contribution guidelines.

Changelog

See CHANGELOG.md.

Upgrades

You can read about how to migrate to the new version here.

Documentation

You can find guides and tutorials in the docs directory.

Copyright and License

Copyright 2018 Box, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

spout

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way
PHP
4,219
star
2

t3js

DEPRECATED - A minimal component-based JavaScript framework
JavaScript
1,557
star
3

Anemometer

Box SQL Slow Query Monitor
JavaScript
1,369
star
4

kube-applier

kube-applier enables automated deployment and declarative configuration for your Kubernetes cluster.
Go
630
star
5

kube-iptables-tailer

A service for better network visibility for your Kubernetes clusters.
Go
538
star
6

box-ui-elements

React Components for Box's Design System and Pluggable Components
JavaScript
532
star
7

box-python-sdk

Box SDK for Python
Python
420
star
8

mojito

An automation platform that enables continuous localization.
Java
367
star
9

flaky

Plugin for nose or pytest that automatically reruns flaky tests.
Python
347
star
10

viewer.js

A viewer for documents converted with the Box View API
JavaScript
335
star
11

stalker

A jQuery plugin allowing elements to follow the user as they scroll a page.
JavaScript
227
star
12

boxcli

A command line interface for interacting with the Box API.
JavaScript
197
star
13

box-windows-sdk-v2

Windows SDK for v2 of the Box API. The SDK is built upon .NET Framework 4.5
C#
186
star
14

ClusterRunner

ClusterRunner makes it easy to parallelize test suites across your infrastructure in the fastest and most efficient way possible.
Python
180
star
15

augmented_types

A PHP extension to enforce parameter and return type annotations
C++
166
star
16

bart

A collection of our critical PHP tools
PHP
163
star
17

box-java-sdk

The Box SDK for Java.
Java
156
star
18

memsniff

A tool for recording and displaying statistics on memcached traffic written in golang.
Go
143
star
19

genty

Genty, pronounced "gen-tee", stands for "generate tests". It promotes generative testing, where a single test can execute over a variety of input.
Python
119
star
20

box-ios-sdk

iOS SDK for the Box Content API
Swift
117
star
21

kube-exec-controller

An admission controller service and kubectl plugin to handle container drift in K8s clusters
Go
109
star
22

RainGauge

RainGauge
JavaScript
107
star
23

box-content-preview

JavaScript library for rendering files stored on Box
JavaScript
105
star
24

leche

DEPRECATED - Testing extensions for Mocha and Sinon
JavaScript
103
star
25

box-openapi

OpenAPI 3.0 Specification for the Box APIs
JavaScript
93
star
26

rotunicode

Python library for converting between a string of ASCII and Unicode chars maintaining readability
Python
77
star
27

brainy

A faster, safer templating library for PHP
PHP
66
star
28

mysqlutilities

Box's MySQL Utilities
Shell
65
star
29

samples

Code snippets and samples to demonstrate how to get the most out of the Box platform & API
JavaScript
64
star
30

box-android-sdk

Java
62
star
31

box-salesforce-sdk

This is the Salesforce SDK for integrating with the Box Platform.
Apex
57
star
32

box-android-apptoapp-sdk

This SDK supports Box OneCloud integrations on Android that handle file ‘roundtrips’. That is, it enables file open-edit-save scenarios between the Box app and partner apps without the need for partner apps to authenticate a Box user independently.
Java
57
star
33

fast_assert

PHP
37
star
34

StatusWolf

Configurable operations dashboard designed to bring together the disparate datasources that operations teams need to manage and present them in a flexible and beautiful way.
PHP
36
star
35

shmock

SHorthand for MOCKing in PHPUnit
PHP
34
star
36

Makefile.test

A makefile used for running test executables
Python
32
star
37

error-reporting-with-kubernetes-events

A demonstration of how Box utilizes Kubernetes CustomResourceDefinitions and Events
Go
32
star
38

box-skills-kit-nodejs

Official toolkit library and boilerplate code for developing Box Skills.
JavaScript
27
star
39

box-python-sdk-gen

Repository for generated Box Python SDK
Python
26
star
40

shalam

DEPRECATED - A friendly tool for CSS spriting
JavaScript
25
star
41

developer.box.com

Box Developer Documentation - Content & Configuration
JavaScript
24
star
42

box-ios-browse-sdk

Objective-C
18
star
43

wavectl

Command Line Client For Wavefront
Python
18
star
44

box-ios-preview-sdk

Box iOS Preview SDK
Swift
17
star
45

clusterrunner-javascript-sdk

ClusterRunner JavaScript SDK that works in both node and browsers
HTML
16
star
46

box-typescript-sdk-gen

Repository for generated Box TS SDK
TypeScript
15
star
47

box-ui-elements-demo

Demo react app for UI Elements
JavaScript
14
star
48

sdks

SDKs, CLI and other tools for using Box Platform
14
star
49

box-android-preview-sdk

Box Android Preview SDK
Java
13
star
50

box-android-browse-sdk

Java
12
star
51

hdrCompressor

Tool for saving HDR file as RGBM, RGBD, RGBE or LogLuv TGA file.
C
12
star
52

box-annotations

JavaScript library for annotations on files rendered with Box Content Preview
TypeScript
11
star
53

etcdb

Etcd PEP 249 driver.
Python
10
star
54

box-content-preview-demo

Demo React App using the Preview UI Element
JavaScript
8
star
55

box-postman

The official Box Postman Collection
JavaScript
7
star
56

box-dotnet-sdk-gen

Repository for Box .NET autogenerated SDK
C#
6
star
57

verold.github.io

Verold developer docs and tutorials
JavaScript
5
star
58

uploaders

Write your own custom uploader to send 3D models/textures to Verold Studio.
4
star
59

box-ios-share-sdk

Objective-C
4
star
60

box-windows-metadata-sdk-v2

Box Metadata C# SDK Plugin
C#
4
star
61

homebrew-mojito

Homebrew tap for Box/mojito
Ruby
3
star
62

box-developer-changelog

Box Developer Changelog
JavaScript
3
star
63

box-languages

Languages used by other box projects
JavaScript
2
star
64

box-android-share-sdk

Java
2
star
65

puppet-clusterrunner

Installs ClusterRunner using Puppet
Puppet
2
star
66

box-java-sdk-samples

Sample apps for the Box Java SDK.
Java
2
star
67

cla

Landing page for CLA Agreements
1
star