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!
Before we jump in, make sure you've got:
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
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!
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'); };
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); }
Want to level up? Here are some advanced techniques:
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; };
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; };
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); });
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!