Back

Step by Step Guide to Building a ServiceTitan API Integration in JS

Aug 15, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of ServiceTitan API integration? You're in for a treat. ServiceTitan's API is a powerful tool that can supercharge your field service management solutions. In this guide, we'll walk through building a robust integration that'll have you manipulating customer data, jobs, and invoices like a pro.

Prerequisites

Before we jump in, make sure you've got:

  • A ServiceTitan account with API credentials (if you don't have these, go bug your account manager!)
  • Node.js and npm installed on your machine
  • A good grasp of JavaScript and REST APIs (but you knew that already, right?)

Setting up the project

Let's get our hands dirty:

mkdir servicetitan-integration cd servicetitan-integration npm init -y npm install axios dotenv

Create a .env file for your API credentials:

ST_CLIENT_ID=your_client_id
ST_CLIENT_SECRET=your_client_secret

Authentication

ServiceTitan uses OAuth 2.0. Here's how to get that access token:

const axios = require('axios'); require('dotenv').config(); async function getAccessToken() { try { const response = await axios.post('https://auth.servicetitan.io/connect/token', { grant_type: 'client_credentials', client_id: process.env.ST_CLIENT_ID, client_secret: process.env.ST_CLIENT_SECRET, }); return response.data.access_token; } catch (error) { console.error('Error getting access token:', error); } }

Pro tip: Implement a token refresh mechanism to keep your integration running smoothly.

Making API requests

Now that we're authenticated, let's make some requests:

async function makeApiRequest(endpoint, method = 'GET', data = null) { const token = await getAccessToken(); try { const response = await axios({ method, url: `https://api.servicetitan.io/v2/${endpoint}`, headers: { Authorization: `Bearer ${token}` }, data, }); return response.data; } catch (error) { console.error(`Error making API request to ${endpoint}:`, error); } }

Remember to handle pagination and errors like a champ!

Implementing key endpoints

Let's tackle some essential endpoints:

Customers

async function getCustomers() { return await makeApiRequest('customers'); }

Jobs

async function createJob(customerId, jobData) { return await makeApiRequest(`customers/${customerId}/jobs`, 'POST', jobData); }

Invoices

async function getInvoices(jobId) { return await makeApiRequest(`jobs/${jobId}/invoices`); }

Data synchronization

Want real-time updates? Implement webhooks:

const express = require('express'); const app = express(); app.post('/webhook', (req, res) => { // Handle the webhook payload console.log('Received webhook:', req.body); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));

Best practices

  • Respect rate limits (ServiceTitan will thank you)
  • Implement caching to reduce API calls
  • Keep your credentials safe (no committing .env files to GitHub!)

Testing and debugging

Unit tests are your friends:

const { getCustomers } = require('./api'); test('getCustomers returns an array', async () => { const customers = await getCustomers(); expect(Array.isArray(customers)).toBe(true); });

Deployment considerations

When you're ready to go live:

  • Consider serverless options for easy scaling
  • Set up monitoring and alerting
  • Keep an eye on your API usage

Conclusion

And there you have it! You're now equipped to build a robust ServiceTitan API integration. Remember, the key to a great integration is understanding the API docs, handling errors gracefully, and staying up to date with API changes.

Happy coding, and may your integrations always be bug-free!

Advanced topics

Feeling adventurous? Look into:

  • Batch operations for processing large datasets
  • Custom field mapping for tailored integrations
  • Integrating with other systems for a unified workflow

The sky's the limit with what you can build. Now go forth and integrate!