How can I parse just the bug count from the PivotalTracker API?

187 Views Asked by At

I'm currently issuing a GET request to the PivotalTracker API to get all of the bugs for a given project, by bug severity. All I really need is a count of the bugs (i.e. 10 critical bugs), but I'm currently getting all of the raw data for each bug in XML format. The XML data has a bug count at the top, but I have to scroll up tons of data to get to that count.

To solve this issue, I'm trying to parse the XML to only display the bug count, but I'm not sure how to do that. I've experimented with Nokogiri and REXML, but it seems like they can only parse actual XML files, not XML from an HTTP GET request.

Here is my code (The access token as been replaced with *'s for security reasons):

require 'net/http'
require 'rexml/document'

prompt = '> '
puts "What is the id of the Project you want to get data from?"
print prompt
project_id = STDIN.gets.chomp()
puts "What type of bugs do you want to get?"
print prompt
type = STDIN.gets.chomp()


def bug(project_id, type)
  net = Net::HTTP.new("www.pivotaltracker.com")
  request = Net::HTTP::Get.new("/services/v3/projects/#{project_id}/stories?filter=label%3Aqa-#{type}")
  request.add_field("X-TrackerToken", "*******************")
  net.read_timeout = 10
  net.open_timeout = 10

  response = net.start do |http|
    http.request(request)
  end
  puts response.code
  print response.read_body
end

bug(project_id, type)

Like I said, the GET request is successfully printing a bug count and all of the raw data for each individual bug to my Terminal window, but I only want it to print the bug count.

1

There are 1 best solutions below

0
On BEST ANSWER

The API documentation shows the total bug count is an attribute of the XML response's top-level node, stories.

Using Nokogiri as an example, try replacing print response.read_body with

xml = Nokogiri::XML.parse(response.body)
puts "Bug count: #{xml.xpath('/stories/@total')}"

Naturally you'll need to add require 'nokogiri' at the top of your code as well.