JavaScript SDK: REST API Access
The Harvest SDK at it's core is a thin wrapper around the Harvest REST API. Any request normally made against the REST API can be made from the JavaScript SDK and Oauth2 access, with these few exceptions:
- Create new user, normally available at
POST /people - Reset password for user, normally available at
PUT /people/#{user_id} - Update user, normally available at
PUT /people/#{user_id} - Delete existing user, normally available at
DELETE /people/#{user_id} - Toggle an existing user, normally available at
POST /people/#{user_id}/toggle
Here is a complete example of accessing the REST API via the SDK:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> <!-- Harvest SDK --> <!--[if lt IE 8]> <script src="//api.harvestapp.com/javascripts/json2.js" type="text/javascript"></script> <![endif]--> <script src="//api.harvestapp.com/javascripts/sdk/sdk.js" type="text/javascript"></script> <script type="text/javascript"> Harvest.Session.client_id( /* Your client_id */ ); network = new Harvest.Network( new Harvest.Session() ); if ( network.is_authenticated() ) { // Make a REST API request to find out who we are. // network.get( '/account/who_am_i', { onComplete: function(response){ $('<a>View your timesheet</a>').attr('href', response['company']['base_uri']+'/daily').appendTo('body'); } }); } else { // Draw a link prompting the user to authenticate, using // the authorization_uri() function. // $('<a>Connect to Harvest</a>').attr('href', network.session.authorization_uri() ).appendTo('body'); } </script> <!-- End Harvest SDK -->
There are only two classes you need to know for start working with the REST API. Harvest.Session, and Harvest.Network.
Harvest.Session settings
To communicate with Harvest using the JavaScript SDK you'll need to receive a set of OAuth 2.0 credentials. Harvest.Session provides access to several configuration.
Harvest.Session.client_id( "#{your_client_id}" )
Your client id identifies your app with Harvest. Keep in mind that when you created your credentials, you provided a redirect url to Harvest. Your app must be hosted on that domain or subdomain for your client id to be valid. Setting a client_id is required to access the Harvest API.
Harvest.Session.host( "#{alternative_api_host}" )
By default, the Harvest JavaScript SDK will make requests against api.harvestapp.com. If you will only have a single Harvest secure site using your integration, you can hard-code this domain as your host. For instance, if we build an integration and only want to run it for our internal Harvest account, we bind the SDK to our subdomain:
Harvest.Session.host( 'iridesco.harvestapp.com' );
Harvest.Session.protocol( "#{alternative_protocol}" )
By default, the Harvest JavaScript SDK makes all requests over https. If you desire an alternative protocol you can specify it here. We strongly discourage you from using plain http for your integration, and may be disabling http for Harvest in the future.
// For example, set plain http. You should not be doing this. Harvest.Session.protocol( 'http://' );
Harvest.Session usage
A Harvest.Session instance manages authentication sessions for the SDK, and you should not need to worry about it much. When you create an instance of Harvest.Network you can access the session at network.session.
// Create a network connection, passing it a new session. // network = new Harvest.Network( new Harvest.Session() ); var uri_for_requesting_authorization = network.session.authorization_uri();
Harvest.Session provides a function credentials() with the current credentials for accessing Harvest. The credentials are fetched from the URL, localStorage, or cookies as is appropriate. You shouldn't need to worry about managing them.
network.session.authorization_uri( optional_return_to_url )
Generate an authorization URI for Harvest. This function provides a URI you can create a link to that will allow users to grant your app access to their account. Usually you use this to create a "Connect to Harvest" button. The optional_return_to_url defaults to the current window.location.
network.session.base_uri()
Generate a base uri from the session protocol and host.
network.session.has_credentials()
A boolean check for if the current user has credentials. If they do, you can proceed to access the REST API on their behalf. If not, you likely want to display a "Connect to Harvest" button with the authorization_uri() generated uri.
network.session.clear()
Manually clear the credentials for this session. This is equivilent to forcing a logout of the user, and will destory their access token.
Harvest.Network usage
The Harvest.Network instance offers direct access to the Harvest REST API, letting you avoid complexities in cross-domain requests and serialization.
network.request( http_method, url, options={} )
Make a request to the Harvest REST API. http_method should be one of GET, POST, PUT, DELETE and url the destination URL. options is an optional object specifying callbacks:
onComplete: function(body, headers) {}- Run upon a successful request, with the body and headers as arguments.onAuthFailure: function(response) {}- Run if the credentials fail upon accessing the server. The default behavior is to flush any existing credentials and reload the page. The full response object is passed, be it an xhr response object or JSON decoded response from ourwindow.namecross-domain request transport.onFailure: function(response) {}- Run on a failed request. The default behavior is to log the response object toconsole.dirand raise an error. The full response object is again passed here, be it an xhr response or JSON decoded response.
Example usage of network.request():
network = new Harvest.Network( new Harvest.Session() ); if ( network.is_authenticated() ) { // Make a REST API request to find out who we are. // network.request( 'GET', '/account/who_am_i', { onComplete: function(response){ $('<a>View your timesheet</a>').attr('href', response['company']['base_uri']+'/daily').appendTo('body'); }, onAuthFailure: function(response) { // Clear credentials, but don't reload the page. Just // call a function to draw the connect screen. network.session.clear(); my_function_to_draw_connect(); }, onFailure: function(response) { // Alert that the request failed and show the status code. // Note that the first response.status is the status on // XHR requests, and response._status is the status on // window.name cross-domain requests (IE7 and other pre-C.O.R.S. // browsers). // alert('Whoops! Http status code: '+(response.status || response._status)); } }); }
network.get( url, options={} ), network.post, network.put, network.delete
These methods call network.request with the stated http_method.
network.is_authenticated()
This is a convenience wrapper for Harvest.Session's network.session.has_credentials(), and is the suggested way to test for an active session.