New Relic API Python Client
The `newrelic-api` library provides a Python interface to interact with the New Relic API v2. It allows users to fetch application data, monitor metrics, and manage various New Relic entities programmatically. Currently at version 1.0.6, it is a community-maintained client that sees infrequent releases, primarily for maintenance and minor enhancements.
Common errors
-
ImportError: cannot import name 'NewRelicApi' from 'newrelic-api'
cause Attempting to import using a hyphen in the package name, which is incorrect for Python modules.fixChange the import statement to use an underscore: `from newrelic_api import NewRelicApi`. -
newrelic_api.exceptions.NewRelicApiException: Invalid API key
cause The provided API key is either incorrect, malformed, or is not the specific 'New Relic REST API Key (v2)' required by the library.fixVerify your API key for typos and ensure it is the correct type of New Relic REST API Key (v2). Regenerate it in New Relic if unsure. -
requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url:
cause You have exceeded the New Relic API rate limits for your account or endpoint.fixReduce the frequency of your API requests. Implement delays between calls or an exponential backoff strategy for retries.
Warnings
- gotcha The `newrelic-api` package specifically requires a 'New Relic REST API Key (v2)'. Using other New Relic keys, such as a License Key or an Insights Insert/Query Key, will result in authentication failures.
- gotcha New Relic's APIs are subject to rate limiting. Making too many requests in a short period will result in `429 Too Many Requests` errors. The library does not implement automatic retry or backoff mechanisms.
- gotcha The Python package name for import is `newrelic_api` (with an underscore), while the PyPI installation name is `newrelic-api` (with a hyphen). This is a common source of `ImportError`.
Install
-
pip install newrelic-api
Imports
- NewRelicApi
from newrelic-api import NewRelicApi
from newrelic_api import NewRelicApi
Quickstart
import os
from newrelic_api import NewRelicApi
# Get your New Relic REST API Key (v2) from environment variable
# Ensure it's not a License Key or Insights Key
NEW_RELIC_API_KEY = os.environ.get('NEW_RELIC_API_KEY', '')
if not NEW_RELIC_API_KEY:
print("Error: NEW_RELIC_API_KEY environment variable not set.")
exit(1)
api = NewRelicApi(api_key=NEW_RELIC_API_KEY)
try:
# Fetch all applications associated with the API key
applications = api.get_applications()
print(f"Found {len(applications)} applications:")
for app in applications:
print(f" ID: {app.get('id')}, Name: {app.get('name')}")
# Example: Get a specific application by ID (replace with a real ID)
if applications:
first_app_id = applications[0]['id']
specific_app = api.get_application(first_app_id)
print(f"\nDetails for first application ({first_app_id}): {specific_app.get('name')}")
except Exception as e:
print(f"An error occurred: {e}")