Connect to the NowMetrix REST API
Create an API key, send it securely with every request, and verify the connection with a small account-context response before requesting analytics data.
1. Create and protect an API key
Sign in to NowMetrix, open Settings → API, and generate your personal API key. Copy it immediately: the complete key is shown only once.
NOWMETRIX_API_KEY=nm_YOUR_KEY
Regenerating or revoking the key invalidates the previous value. The key can only access trackers assigned to its NowMetrix user.
2. Send the key with every request
The REST API is stateless: there is no separate login request or persistent session. Send the API key as a Bearer token on every HTTPS request.
GET https://api.nowmetrix.com/api/me
Authorization: Bearer nm_YOUR_KEY
Accept: application/json
- Base URL:
https://api.nowmetrix.com - Authentication:
Authorization: Bearer nm_YOUR_KEY - Connection test:
GET /api/merequires no tracker parameter. - Timeouts: set a finite connection and response timeout in every client.
3. Verify the connection with cURL
Use cURL for the quickest connection check from a terminal.
API_KEY="nm_YOUR_KEY"
curl --fail-with-body --silent --show-error \
--header "Authorization: Bearer ${API_KEY}" \
--header "Accept: application/json" \
"https://api.nowmetrix.com/api/me"
A successful request returns HTTP 200 and the trackers available to the API key:
{
"authenticated": true,
"current_tracker": "TRACKER_ID",
"trackers": [
{
"tracker": "TRACKER_ID",
"host": "example-media.test"
},
{
"tracker": "SECOND_TRACKER_ID",
"host": "example-studio.test"
}
]
}
PHP 8+
Use PHP's cURL extension and keep the API key in an environment variable.
<?php
$apiKey = getenv('NOWMETRIX_API_KEY');
if (!is_string($apiKey) || $apiKey === '') {
throw new RuntimeException('NOWMETRIX_API_KEY is not set.');
}
$curl = curl_init('https://api.nowmetrix.com/api/me');
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Accept: application/json',
],
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($curl);
if ($body === false) {
$error = curl_error($curl);
curl_close($curl);
throw new RuntimeException($error);
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
if ($status < 200 || $status >= 300) {
throw new RuntimeException("NowMetrix API returned HTTP {$status}: {$body}");
}
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
print_r($data);
JavaScript (Node.js 18+)
Use the built-in fetch API on the server. Do not expose the API key in browser-side JavaScript.
const apiKey = process.env.NOWMETRIX_API_KEY;
if (!apiKey) throw new Error('NOWMETRIX_API_KEY is not set.');
async function main() {
const response = await fetch('https://api.nowmetrix.com/api/me', {
headers: {
Authorization: `Bearer ${apiKey}`,
Accept: 'application/json',
},
signal: AbortSignal.timeout(10_000),
});
const body = await response.text();
if (!response.ok) {
throw new Error(`NowMetrix API returned HTTP ${response.status}: ${body}`);
}
console.log(JSON.parse(body));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Python 3
The requests package provides a concise client with explicit timeout and status handling. Install it with python -m pip install requests.
import os
import requests
api_key = os.environ["NOWMETRIX_API_KEY"]
response = requests.get(
"https://api.nowmetrix.com/api/me",
headers={
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
},
timeout=10,
)
response.raise_for_status()
print(response.json())
Java 11+
Java's standard HttpClient is sufficient for the authenticated request.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class NowMetrixExample {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("NOWMETRIX_API_KEY");
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalStateException("NOWMETRIX_API_KEY is not set.");
}
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.nowmetrix.com/api/me"))
.timeout(Duration.ofSeconds(10))
.header("Authorization", "Bearer " + apiKey)
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException(
"NowMetrix API returned HTTP " + response.statusCode() + ": " + response.body()
);
}
System.out.println(response.body());
}
}
C# (.NET 6+)
Use HttpClient with a Bearer authorization header and an application-level timeout.
using System.Net.Http.Headers;
var apiKey = Environment.GetEnvironmentVariable("NOWMETRIX_API_KEY")
?? throw new InvalidOperationException("NOWMETRIX_API_KEY is not set.");
using var client = new HttpClient
{
BaseAddress = new Uri("https://api.nowmetrix.com"),
Timeout = TimeSpan.FromSeconds(10),
};
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
using var response = await client.GetAsync("/api/me");
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(
$"NowMetrix API returned HTTP {(int)response.StatusCode}: {body}"
);
}
Console.WriteLine(body);
Go 1.20+
Use the standard net/http client and decode the JSON response into a generic structure or your own types.
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
func main() {
apiKey := os.Getenv("NOWMETRIX_API_KEY")
if apiKey == "" {
panic("NOWMETRIX_API_KEY is not set")
}
request, err := http.NewRequest(http.MethodGet, "https://api.nowmetrix.com/api/me", nil)
if err != nil {
panic(err)
}
request.Header.Set("Authorization", "Bearer "+apiKey)
request.Header.Set("Accept", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode >= 300 {
panic("NowMetrix API returned " + response.Status)
}
var data map[string]any
if err := json.NewDecoder(response.Body).Decode(&data); err != nil {
panic(err)
}
fmt.Printf("%#v\n", data)
}
Ruby 3+
Ruby's standard library can make the request without an additional HTTP package.
require 'json'
require 'net/http'
api_key = ENV.fetch('NOWMETRIX_API_KEY')
uri = URI('https://api.nowmetrix.com/api/me')
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Bearer #{api_key}"
request['Accept'] = 'application/json'
response = Net::HTTP.start(
uri.hostname,
uri.port,
use_ssl: true,
open_timeout: 10,
read_timeout: 10
) { |http| http.request(request) }
unless response.is_a?(Net::HTTPSuccess)
raise "NowMetrix API returned HTTP #{response.code}: #{response.body}"
end
puts JSON.pretty_generate(JSON.parse(response.body))
Handle authentication and transport errors
Check the HTTP status before decoding a success payload. Error responses use a stable JSON structure with a machine-readable error.code.
401 missing_token: the Authorization header is missing.401 invalid_token: the key is invalid, revoked, or was replaced.403 site_not_authorized: the key cannot access the requested tracker.429 rate_limit_exceeded: wait for theRetry-Afterinterval before retrying.503: retry temporary backend failures with bounded exponential backoff.
{
"error": {
"code": "invalid_token",
"message": "Bearer token is invalid or revoked."
}
}
Use a tracker-specific endpoint
Read current_tracker or a trackers[].tracker value from /api/me, then pass that tracker ID as the site query parameter.
GET https://api.nowmetrix.com/v1/realtime?site=TRACKER_ID
Authorization: Bearer nm_YOUR_KEY
Accept: application/json