Back

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

Aug 15, 20246 minute read

Hey there, fellow dev! Ready to dive into the world of PagerDuty API integration? Let's roll up our sleeves and get coding!

Introduction

PagerDuty's API is a powerhouse for incident management. We're going to build an integration that'll make your life easier and your incidents more manageable. Trust me, your future self will thank you.

Prerequisites

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

  • A PagerDuty account (duh!)
  • Node.js up and running
  • Your shiny PagerDuty API key

Got all that? Great! Let's move on.

Setting up the project

First things first, let's get our project off the ground:

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

Authentication

Time to get cozy with that API key. Create a .env file and add:

PAGERDUTY_API_KEY=your_api_key_here

Now, let's set up our headers:

require('dotenv').config(); const headers = { 'Authorization': `Token token=${process.env.PAGERDUTY_API_KEY}`, 'Accept': 'application/vnd.pagerduty+json;version=2' };

Making API requests

Let's take our first step into the PagerDuty API world:

const axios = require('axios'); async function getIncidents() { try { const response = await axios.get('https://api.pagerduty.com/incidents', { headers }); console.log(response.data); } catch (error) { console.error('Error fetching incidents:', error.response.data); } }

Core integration features

Retrieving incidents

We've already got this one covered with our getIncidents function. Easy peasy!

Creating incidents

Let's spice things up and create an incident:

async function createIncident(title, serviceId) { try { const response = await axios.post('https://api.pagerduty.com/incidents', { incident: { type: 'incident', title: title, service: { id: serviceId, type: 'service_reference' } } }, { headers }); console.log('Incident created:', response.data); } catch (error) { console.error('Error creating incident:', error.response.data); } }

Updating incident status

Time to resolve that pesky incident:

async function updateIncidentStatus(incidentId, status) { try { const response = await axios.put(`https://api.pagerduty.com/incidents/${incidentId}`, { incident: { type: 'incident', status: status } }, { headers }); console.log('Incident updated:', response.data); } catch (error) { console.error('Error updating incident:', error.response.data); } }

Fetching on-call schedules

Who's on call? Let's find out:

async function getOnCallSchedules() { try { const response = await axios.get('https://api.pagerduty.com/schedules', { headers }); console.log('On-call schedules:', response.data); } catch (error) { console.error('Error fetching schedules:', error.response.data); } }

Webhooks implementation

PagerDuty can talk back! Let's set up a simple Express server to listen for webhooks:

const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { console.log('Received webhook:', req.body); res.status(200).send('OK'); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));

Error handling and best practices

Remember, PagerDuty has rate limits. Be nice and don't hammer the API. Also, always check for error responses and handle them gracefully. Your future debugging self will be grateful.

Testing the integration

Unit testing is your friend. Here's a quick example using Jest:

test('getIncidents fetches incidents successfully', async () => { const mockResponse = { data: { incidents: [] } }; axios.get.mockResolvedValue(mockResponse); await getIncidents(); expect(axios.get).toHaveBeenCalledWith('https://api.pagerduty.com/incidents', { headers }); });

Deployment considerations

When deploying, remember to:

  • Use environment variables for sensitive info
  • Set up proper error logging
  • Consider using a caching layer for frequently accessed data

Conclusion

And there you have it! You've just built a solid PagerDuty API integration. You're now armed with the power to manage incidents like a pro. Remember, the PagerDuty API docs are your best friend for diving deeper.

Now go forth and keep those incidents under control! Happy coding!