• /
  • EnglishEspañol日本語한국어Português
  • 로그인지금 시작하기

Fetch data from a third-party service

This lesson is part of a course that teaches you how to build a New Relic application from the ground up. If you haven't already, check out the Overview.

Each lesson in the course builds upon the last, so make sure you've completed the last lesson, Access NerdStorageVault from your nerdlet, before starting this one.

In previous lessons, you learned of a third-party service that you can use to fetch mock cancellation data for the Total cancellations per version chart in your New Relic application. Even though the data in this service is fake, the real value of this lesson is learning how you can use third party services to supply data to your New Relic application.

If you make a request to the mock service with cancellation data (https://api.nerdsletter.net/cancellations) you'll see a response rejecting your request with a message that reads "Unauthorized":

bash
$
curl https://api.nerdsletter.net/cancellations
Unauthorized

This is because the Nerdsletter API requires an Authorization header. More specifically, you must pass a bearer token of ABC123 to gain authorized access to its data. If you make a request to the service with the header Authorization: Bearer ABC123, you'll get a successful response with the mocked cancellation data:

bash
$
curl https://api.nerdsletter.net/cancellations -H 'Authorization: Bearer ABC123'
{"a": 15, "b": 78}

In the last lesson, you used NerdGraph to store this API token in your New Relic application's NerdStorageVault data store. You also passed the token to your TotalCancellations component and logged its use to your browser's console. In this lesson, you follow up that log statement with a real request to the Nerdsletter API using your authorization token. Then, you supply the data from that external resource to your Total cancellations per version chart.

Change to the third-party-services/ab-test directory of the coursework repository:

bash
$
cd nru-programmability-course/third-party-services/ab-test

This directory contains the code that we expect your application to have at this point in the course. By navigating to the correct directory at the start of each lesson, you leave your custom code behind, thereby protecting yourself from carrying incorrect code from one lesson to the next.

In nerdlets/ab-test-nerdlet/total-cancellations.js, make a request to api.nerdsletter.net with your API token. Save the results to state, and use that state in render():

import React from 'react';
import { HeadingText, PieChart } from 'nr1';
export default class TotalCancellations extends React.Component {
constructor() {
super(...arguments);
this.state = {
cancellations: [],
lastToken: null
}
}
generateChartData(data) {
const cancellationsA = data ? data.a : 0;
const cancellationsB = data ? data.b : 0;
return [
{
metadata: {
id: 'cancellations-A',
name: 'Version A',
viz: 'main',
color: 'blue',
},
data: [
{ y: cancellationsA },
],
},
{
metadata: {
id: 'cancellations-B',
name: 'Version B',
viz: 'main',
color: 'green',
},
data: [
{ y: cancellationsB },
],
},
]
}
componentDidUpdate() {
if (this.props.token && this.props.token != this.state.lastToken) {
console.log(`Requesting data with api token ${this.props.token}`)
fetch(
"https://api.nerdsletter.net/cancellations",
{headers: {"Authorization": `Bearer ${this.props.token}`}}
).then(
(response) => {
if (response.status == 200) {
return response.json()
} else if (response.status == 401) {
console.error("Incorrect auth header")
} else {
console.error(response.text())
}
}
).then(
(data) => {
if (data) {
this.setState({
cancellations: this.generateChartData(data),
lastToken: this.props.token
})
}
}
)
}
}
render() {
return <div>
<HeadingText className="chartHeader">
Total cancellations per version
</HeadingText>
<PieChart data={this.state.cancellations} fullWidth />
</div>
}
}

In this code, you initialize TotalCancellations.state.cancellations with zero for the y-value in each series instead of the previously hardcoded values. This helps to more realistically represent what the chart should show if your New Relic app hasn't successfully requested data from the Nerdsletter API. Next, you use Javascript's fetch() function to make an HTTP request to the Nerdsletter API. You then pass your token in the request's Authorization header. If the request is successful, you update the cancellation data in TotalCancellations.state so that that data is reflected in the component's render method.

Navigate to the root of your Nerdpack at nru-programmability-course/third-party-service/ab-test.

Generate a new UUID for your Nerdpack:

bash
$
nr1 nerdpack:uuid -gf

Because you cloned the coursework repository that contained an existing Nerdpack, you need to generate your own unique identifier. This UUID maps your Nerdpack to your New Relic account. It also allows your app to make Nerdgraph requests on behalf of your account.

Serve your application locally:

bash
$
nr1 nerdpack:serve

Go to https://one.newrelic.com?nerdpacks=local, and view your application under Apps > Your apps.

If your token in NerdStorageVault is not "ABC123", then your console will show an error that reads, "Incorrect auth header".

If you set the token to "ABC123", then Total cancellations per version updates to show the values from the third-party service.

If something doesn't work, use your browser's debug tools to try to identify the problem.

Make sure you:

  • Copied the code correctly from the lesson
  • Generated a new UUID
  • Replaced all instances of <YOUR NEW RELIC ACCOUNT ID> in your project with your actual New Relic account ID

When you're finished, stop serving your New Relic application by pressing CTRL+C in your local server's terminal window.

Great job! You've come a long way from running nr1 nerdpack:create for the first time.

You've created eight charts with varying styles and supplied them with dynamic data from multiple sources. You've learned about the New Relic One SDK and used many of its components. You've even gathered data from a third-party service and mixed it seemlessly with your New Relic data to provide a complete look at how the competing versions in your A/B test perform against each other.

From here, there is only one more set of APIs in the New Relic One SDK that you've yet to get your hands on: Platform APIs. These will come in handy in improving the usability of your New Relic application.

This lesson is part of a course that teaches you how to build a New Relic application from the ground up. Continue on to the next lesson: Add PlatformStateContext to your nerdlet.

Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.