New Relic Now Start training on Intelligent Observability February 25th.
Save your seat.

When you're working with large amounts of data or data from many different sources, it's a good idea to use tags to help with organization. While you can tag data manually in New Relic, you can make your workflow more efficient and tag New Relic entities via API calls instead. Need a better way to segment your apps based on environments? You can do it automatically via the API! The Python code snippets in this post show examples of creating, reading, updating, and deleting tags using GraphQL.

Prerequisites

If you plan to follow along with this tutorial and use Python to make your API calls, you need:

The next video shows you how to manage your tags using the NerdGraph API.

Creating tags

Here's an example query for creating a tag using the NerdGraph API. If you need more context on the starter code, see Using Python to make an API call in part one of this series.

import requests
import json
from license import user_key

def nerdgraph_createtags(key):
  # GraphQL query to NerdGraph
  query = """
  mutation {
    taggingAddTagsToEntity(
        guid: "XXX",
        tags: [
          	{ key: "env", values: ["prod"]}, 
          	{ key: "cloud", values: ["AWS", "ap-southeast"]},
            { key: "team", values: ["web", "content", "frontend"]}
        		]) {
            errors {
                message
            }
        }
  }"""

  # NerdGraph endpoint 
  endpoint = "https://api.newrelic.com/graphql"
  headers = {'API-Key': f'{key}'}
  response = requests.post(endpoint, headers=headers, json={"query": query})
  
  if response.status_code == 200: 
    # convert a JSON into an equivalent python dictionary
    dict_response = json.loads(response.content)
    print(dict_response)

    # optional - serialize object as a JSON formatted stream 
    # json_response = json.dumps(response.json(), indent=2)
    # print(json_response)
  else:
    # raise an exepction with a HTTP response code, if there is an error
    raise Exception(f'Nerdgraph query failed with a {response.status_code}.')

nerdgraph_createtags(user_key)

Reading tags

Here's how you can read tags using the NerdGraph API.

import requests
import json
from license import user_key

def nerdgraph_readtags(key):
  # GraphQL query to NerdGraph
  query = """
  {
    actor {
      entitySearch(query: "name = 'XXX'") {
        results {
          entities {
            tags {
              key
              values
            }
            guid
            name
            account {
              name
              id
            }
          }
        }
      }
    }
  }"""

  # NerdGraph endpoint 
  endpoint = "https://api.newrelic.com/graphql"
  headers = {'API-Key': f'{key}'}
  response = requests.post(endpoint, headers=headers, json={"query": query})
  
  if response.status_code == 200: 
    # convert a JSON into an equivalent python dictionary
    dict_response = json.loads(response.content)
    print(dict_response["data"]["actor"]["entitySearch"]["results"]["entities"])

    # optional - serialize object as a JSON formatted stream 
    # json_response = json.dumps(response.json(), indent=2)
    # print(json_response)
  else:
    # raise an exepction with a HTTP response code, if there is an error
    raise Exception(f'Nerdgraph query failed with a {response.status_code}.')

nerdgraph_readtags(user_key)

Updating tags

Here's how you can update dates with the NerdGraph API.

import requests
import json
from license import user_key

def nerdgraph_updatetags(key):
  # GraphQL query to NerdGraph
  query = """
  mutation {
    taggingReplaceTagsOnEntity(
        guid: "XXX",
        tags: [
          	{ key: "env", values: ["staging"]}, 
          	{ key: "cloud", values: ["AWS", "ap-southeast"]},
            { key: "team", values: ["web", "content", "frontend"]}
        		]) {
            errors {
                message
            }
        }
  }"""

  # NerdGraph endpoint 
  endpoint = "https://api.newrelic.com/graphql"
  headers = {'API-Key': f'{key}'}
  response = requests.post(endpoint, headers=headers, json={"query": query})
  
  if response.status_code == 200: 
    # convert a JSON into an equivalent python dictionary
    dict_response = json.loads(response.content)
    print(dict_response)

    # optional - serialize object as a JSON formatted stream 
    # json_response = json.dumps(response.json(), indent=2)
    # print(json_response)
  else:
    # raise an exepction with a HTTP response code, if there is an error
    raise Exception(f'Nerdgraph query failed with a {response.status_code}.')

nerdgraph_updatetags(user_key)

Deleting tags

Here's how to delete tags using the NerdGraph API.

import requests
import json
from license import user_key

def nerdgraph_deletetags(key):
  # GraphQL query to NerdGraph
  query = """
  mutation {
      taggingDeleteTagFromEntity(
          guid: "XXX",
          tagKeys: ["env", "team"]) {
              errors {
                  message
              }
          }
  }"""

  # NerdGraph endpoint 
  endpoint = "https://api.newrelic.com/graphql"
  headers = {'API-Key': f'{key}'}
  response = requests.post(endpoint, headers=headers, json={"query": query})
  
  if response.status_code == 200: 
    # convert a JSON into an equivalent python dictionary
    dict_response = json.loads(response.content)
    print(dict_response)

    # optional - serialize object as a JSON formatted stream 
    # json_response = json.dumps(response.json(), indent=2)
    # print(json_response)
  else:
    # raise an exepction with a HTTP response code, if there is an error
    raise Exception(f'Nerdgraph query failed with a {response.status_code}.')

nerdgraph_deletetags(user_key)

To learn more, see the NerdGraph tutorial on tags.

Stay tuned for part three in the series, where you'll learn how to export your telemetry data with Python and the NerdGraph API.

Interested in what else New Relic has to offer? Check out our Infrastructure monitoring platform.