Back

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

Aug 3, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of ServiceNow API integration? You're in for a treat. We'll be using the @servicenow/sdk package to make our lives easier. Let's get cracking!

Prerequisites

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

  • Node.js and npm (you're a pro, so I'm sure you've got this covered)
  • Access to a ServiceNow instance (if you don't have one, no worries – you can sign up for a free developer instance)
  • Your JavaScript skills sharpened and ready to go

Setting up the project

Let's kick things off by setting up our project:

mkdir servicenow-api-integration cd servicenow-api-integration npm init -y npm install @servicenow/sdk

Configuring the ServiceNow connection

Now, let's get our ServiceNow connection up and running:

const { ServiceNowClient } = require('@servicenow/sdk'); const client = new ServiceNowClient({ instance: 'your-instance.service-now.com', auth: { username: 'your-username', password: 'your-password' } });

Pro tip: For production, consider using OAuth instead of basic auth. Your future self will thank you!

Making API requests

Time to make some requests! Here's a quick rundown:

// GET request const getIncidents = async () => { const response = await client.get('/api/now/table/incident'); console.log(response.data.result); }; // POST request const createIncident = async () => { const response = await client.post('/api/now/table/incident', { short_description: 'Coffee machine is broken', urgency: '2' }); console.log(response.data.result); }; // PUT request const updateIncident = async (sysId) => { const response = await client.put(`/api/now/table/incident/${sysId}`, { state: '2' }); console.log(response.data.result); }; // DELETE request const deleteIncident = async (sysId) => { await client.delete(`/api/now/table/incident/${sysId}`); console.log('Incident deleted'); };

Handling responses

Always expect the unexpected:

try { const response = await client.get('/api/now/table/incident'); const incidents = response.data.result; // Do something with the incidents } catch (error) { console.error('Oops! Something went wrong:', error.message); }

Advanced topics

Want to level up? Here are some advanced techniques:

Pagination

const getAllIncidents = async () => { let offset = 0; const limit = 100; let allIncidents = []; while (true) { const response = await client.get('/api/now/table/incident', { params: { sysparm_limit: limit, sysparm_offset: offset } }); const incidents = response.data.result; if (incidents.length === 0) break; allIncidents = allIncidents.concat(incidents); offset += limit; } return allIncidents; };

Filtering and sorting

const getHighPriorityIncidents = async () => { const response = await client.get('/api/now/table/incident', { params: { sysparm_query: 'priority=1^ORpriority=2', sysparm_order_by: 'opened_at', sysparm_order: 'desc' } }); return response.data.result; };

Best practices

  • Respect rate limits: ServiceNow might throttle you if you go too fast
  • Log everything: Your future debugging self will be grateful
  • Keep your secrets secret: Use environment variables for sensitive info

Testing the integration

Don't forget to test! Here's a quick Jest example:

test('should get incidents', async () => { const incidents = await getIncidents(); expect(incidents).toBeDefined(); expect(incidents.length).toBeGreaterThan(0); });

Conclusion

And there you have it! You're now equipped to build robust ServiceNow API integrations. Remember, the @servicenow/sdk package is your friend – it's got your back with a ton of features we didn't even touch on here.

Keep exploring, keep coding, and most importantly, keep having fun with it. Happy integrating!