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.
Before we jump in, make sure you've got:
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
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.
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!
Let's tackle some essential endpoints:
async function getCustomers() { return await makeApiRequest('customers'); }
async function createJob(customerId, jobData) { return await makeApiRequest(`customers/${customerId}/jobs`, 'POST', jobData); }
async function getInvoices(jobId) { return await makeApiRequest(`jobs/${jobId}/invoices`); }
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'));
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); });
When you're ready to go live:
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!
Feeling adventurous? Look into:
The sky's the limit with what you can build. Now go forth and integrate!