Back

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

Aug 3, 20244 minute read

Introduction

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

Prerequisites

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

  • Ruby installed (I know you probably do, but just checking!)
  • A ServiceNow instance and API credentials (if you don't have these, go bug your admin)

Setting up the project

First things first, let's get our project set up:

gem install servicenow-api mkdir servicenow_integration cd servicenow_integration touch servicenow_client.rb

Configuring the ServiceNow client

Now, let's write some code! Open up servicenow_client.rb and add:

require 'servicenow-api' client = ServiceNow::Client.new( instance: 'your_instance', username: 'your_username', password: 'your_password' )

Replace those placeholder values with your actual credentials. Easy peasy!

Basic API operations

Let's cover the CRUD operations. Here's how you can:

Retrieve records:

incidents = client.get('incident')

Create a record:

new_incident = client.post('incident', { short_description: 'Coffee machine is broken!' })

Update a record:

client.put('incident', sys_id: 'abc123', state: 'In Progress')

Delete a record:

client.delete('incident', 'abc123')

Advanced usage

Want to level up? Try these:

Querying with filters:

high_priority = client.get('incident', query: { priority: 1 })

Handling attachments:

client.attach('incident', 'abc123', '/path/to/file.pdf')

Working with custom tables:

custom_records = client.get('u_my_custom_table')

Error handling and best practices

Always wrap your API calls in a begin/rescue block:

begin result = client.get('incident') rescue ServiceNow::Error => e puts "Oops! #{e.message}" end

And don't forget to respect rate limits. Be nice to the API!

Testing the integration

Testing is crucial. Here's a quick example using RSpec:

RSpec.describe ServiceNow::Client do it 'retrieves incidents' do client = ServiceNow::Client.new(instance: 'test', username: 'test', password: 'test') allow(client).to receive(:get).and_return([{ number: 'INC0001' }]) expect(client.get('incident')).to eq([{ number: 'INC0001' }]) end end

Deployment considerations

When deploying, use environment variables for your credentials:

client = ServiceNow::Client.new( instance: ENV['SERVICENOW_INSTANCE'], username: ENV['SERVICENOW_USERNAME'], password: ENV['SERVICENOW_PASSWORD'] )

Conclusion

And there you have it! You're now equipped to build awesome ServiceNow integrations with Ruby. Remember, the servicenow-api gem documentation is your friend if you need more details.

Now go forth and automate all the things! 🚀