Hey there, fellow developer! Ready to supercharge your incident management with PagerDuty's API? In this guide, we'll walk through building a Ruby integration that'll have you managing incidents like a pro. Let's dive in!
Before we start coding, make sure you've got:
Got those? Great! Let's get our hands dirty.
First things first, let's set up our project:
mkdir pagerduty_integration cd pagerduty_integration bundle init
Now, add these gems to your Gemfile:
gem 'httparty' gem 'dotenv'
Run bundle install
, and we're off to the races!
PagerDuty uses API keys for authentication. Let's keep it secure:
.env
file in your project rootPAGERDUTY_API_KEY=your_api_key_here
Now, let's set up our HTTP client:
require 'httparty' require 'dotenv/load' class PagerDutyClient include HTTParty base_uri 'https://api.pagerduty.com' headers 'Authorization' => "Token token=#{ENV['PAGERDUTY_API_KEY']}" headers 'Accept' => 'application/vnd.pagerduty+json;version=2' headers 'Content-Type' => 'application/json' end
Let's fetch some incidents:
response = PagerDutyClient.get('/incidents') puts response.body
Creating an incident? Easy peasy:
body = { incident: { type: "incident", title: "The server is on fire!", service: { id: "PIJ90N7", type: "service_reference" } } } response = PagerDutyClient.post('/incidents', body: body.to_json)
PagerDuty returns JSON, so let's parse it:
incidents = JSON.parse(response.body)['incidents']
Don't forget to handle errors:
if response.code != 200 puts "Error: #{response.code} - #{response.message}" end
Want to paginate through results? Here's how:
def get_all_incidents incidents = [] offset = 0 loop do response = PagerDutyClient.get('/incidents', query: { offset: offset, limit: 100 }) new_incidents = JSON.parse(response.body)['incidents'] break if new_incidents.empty? incidents.concat(new_incidents) offset += 100 end incidents end
PagerDuty can send webhooks to your app. Here's a basic Sinatra endpoint:
require 'sinatra' post '/webhook' do payload = JSON.parse(request.body.read) # Process the webhook payload status 200 end
Here's a quick RSpec example:
RSpec.describe PagerDutyClient do it "fetches incidents" do VCR.use_cassette("incidents") do response = PagerDutyClient.get('/incidents') expect(response.code).to eq(200) end end end
When deploying:
And there you have it! You're now equipped to build a robust PagerDuty integration in Ruby. Remember, the PagerDuty API docs are your friend for more advanced features.
Now go forth and conquer those incidents! Happy coding! 🚀