Response-time charts, transaction trace breakdowns, CPU usage—tons of useful data are available on the New Relic Platform. But what if you want to take your data into your own hands?

Since joining New Relic a few months ago, I’ve been getting to know the REST API. In case you aren’t familiar with it, the REST API (v2) can allow you to extract your applications’ raw performance data. It was easy to get started: I made API calls on the command line, using curl commands generated in the API Explorer. Type in a command like:

curl -X GET 'https://api.newrelic.com/v2/applications.json' \
-H 'X-Api-Key: {YOUR_API_KEY}’ -i

and the JSON response spills into the console. Fun!

However, I was interested in making API calls from within an application, not just on the command line. After trying it out, I created a demo app that shows how you can make API requests for metric data such as response time and throughput, the same data used in New Relic charts, from within a Ruby on Rails application. Play with the REST API yourself in this demo and see below for quick tips on how to get started.

Getting started

The REST API demo is straightforward: Select a button to fire off an AJAX call requesting data for a given metric name and value. Using the open-source gem HTTParty, the app makes a GET request to the metric data endpoint and plots the response using d3, a JavaScript library for data bvisualization. The view also displays the HTTParty request, relevant metric names and values, and the query string used on the backend.

The REST API returns metric data as a list of timeslices, or nested objects containing metric data for a given time range. I simplified the handoff to d3 by restructuring the JSON response.

Example JSON response, as seen in the invaluable API Explorer:

{
    "metric_data": {
        "from": "2015-05-03T21:09:13+00:00",
        "to": "2015-05-03T21:39:13+00:00",
        "metrics": [
            {
                "name": "Controller/charts/data",
                "timeslices": [ 
                    {
                        "from": "2015-05-03T21:08:00+00:00",
                        "to": "2015-05-03T21:09:00+00:00",
                        "values": {
                            "throughput": 0.5
                        }
                    },
            {
                "from": "2015-05-03T21:09:00+00:00",
                    "to": "2015-05-03T21:10:00+00:00",
                    "values": {
                        "throughput": 0.5
                    }
                },

            ...
                ]
        ...

In my controller, I remove the metadata and flatten the timeslice objects:

def data
   metric_data = get_api_response

   parsed_data_array = metric_data.map do |data_for_each_metric|
        parse_data(data_for_each_metric)
   end
 
   # render JSON for view here

end

def parse_data(incoming_data)
    parsed_data = {}
    parsed_data["name"] = incoming_data["name"]
    parsed_data["timeslices"] = []

    # create a new key for each timeslice
    # that extracts the single requested value
    incoming_data["timeslices"].each do |timeslice|
    parsed_data["timeslices"] << {
        from: timeslice["from"],
        value: 
        timeslice["values"][params[:value]]
        }
    end
    parsed_data
end

One quick tip for plotting your data over time: Use epoch time for the x-axis. The REST API takes and returns time windows formatted in UTC, but converting the from timestamp in each timeslice from UTC into epoch time made the d3 visualization much simpler.

Test and verify

Once your app is up and running, you can use New Relic Synthetics to verify that you’re getting the data you want. Because the demo app requests its own New Relic performance data, I set up Synthetics monitors that periodically load the page and push buttons. This generates baseline traffic—and thus data to visualize.

A snippet from my monitor script, using Synthetics’ JavaScript-like scripting language:

//This script will go to the API demo app, click a button, and make sure that the API call was 
//successful by checking that the svg element appeared
var By = $driver.By;

// Load the app
$browser.get("https://data-api-demo.herokuapp.com/").then(function(){

    // Click a button
    return $browser.findElement(By.id("avg_response_time")).click();

})
.then(function(){
    // Find and ensure that svg appears within 2 seconds
    $browser.waitForElement($driver.By.id("svg"), 2000);
});

How do you use the New Relic REST API? Tweet your stories at us—we’d love to hear how your raw data comes in handy!

Emily Bookstein is a software engineer at New Relic and an alumna of the all-women bootcamp Hackbright Academy. View posts by .

Interested in writing for New Relic Blog? Send us a pitch!