MeterTrail
← All tutorials

Track your first AI request with Java

Use the Java HTTP client to send a request and model usage, check the receipt and find it in the console.

Before you start

JDK 17 or later, Maven 3.9 or later, a MeterTrail account and a project API key. The provided pom.xml includes Jackson.

Keep project API keys out of browser code, screenshots and source control. No model API key is required for this test.

1. Create a project and API key

Create a free account, verify your email, then create or select a project in Project management. Open API keys for that project, create a key. The first key in a project needs no additional email verification; later keys require it. Save the key when it is displayed.

Create a free account

2. Set your environment

# macOS / Linux / WSL
export METERTRAIL_ENDPOINT="https://metertrail.com"
printf 'Project API key (input is visible): '
IFS= read -r METERTRAIL_API_KEY
export METERTRAIL_API_KEY

# Windows PowerShell (Node.js / Python / Java tutorials)
$env:METERTRAIL_ENDPOINT = "https://metertrail.com"
$env:METERTRAIL_API_KEY = Read-Host "Project API key" -MaskInput

3. Send a sample trace

Save as src/main/java/com/metertrail/example/Send.java and run from the same terminal where you set the environment variables.

Save as pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.metertrail.example</groupId>
  <artifactId>first-request</artifactId>
  <version>1.0.0</version>
  <properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <lombok.version>1.18.48</lombok.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.13.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.22.4</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.4</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.14.1</version>
        <configuration>
          <annotationProcessorPaths>
            <path>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
              <version>${lombok.version}</version>
            </path>
          </annotationProcessorPaths>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.5.0</version>
        <configuration><mainClass>com.metertrail.example.Send</mainClass></configuration>
      </plugin>
    </plugins>
  </build>
</project>

Save as src/main/java/com/metertrail/example/MeterTrailClient.java

package com.metertrail.example;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.metertrail.example.model.BatchReceipt;
import com.metertrail.example.model.BatchRequest;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/** Reuse one client in your application. No model calls or automatic retries. */
public final class MeterTrailClient {
    private final URI batchEndpoint;
    private final String apiKey;
    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;

    public MeterTrailClient(String endpoint, String apiKey) {
        if (endpoint == null || endpoint.isBlank() || apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("endpoint and apiKey are required");
        }
        this.batchEndpoint = URI.create(endpoint.replaceAll("/+
quot;, "") + "/v1/events/batch"); this.apiKey = apiKey; this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); this.objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); } public BatchReceipt sendBatch(BatchRequest batch) throws IOException, InterruptedException { byte[] payload = objectMapper.writeValueAsBytes(batch); HttpRequest request = HttpRequest.newBuilder(batchEndpoint) .timeout(Duration.ofSeconds(10)) .header("Authorization", "Bearer " + apiKey) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofByteArray(payload)).build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 202) { throw new IOException("Upload failed: HTTP " + response.statusCode() + " " + response.body()); } return objectMapper.readValue(response.body(), BatchReceipt.class); } }

Save as src/main/java/com/metertrail/example/model/Agent.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Agent {
    private String serviceName;
    private String environment;
    private String instanceId;
}

Save as src/main/java/com/metertrail/example/model/BatchReceipt.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
@Setter
public class BatchReceipt {
    private String batchId;
    private Integer received;
    private String status;
}

Save as src/main/java/com/metertrail/example/model/BatchRequest.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
import java.util.List;

@Getter
@Setter
public class BatchRequest {
    private String schemaVersion;
    private Agent agent;
    private List<Event<?>> events;
}

Save as src/main/java/com/metertrail/example/model/Event.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Event<T> {
    private String eventId;
    private Long revision;
    private String type;
    private String objectId;
    private String traceId;
    private String spanId;
    private String startedAt;
    private T data;
}

Save as src/main/java/com/metertrail/example/model/ObservationData.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ObservationData {
    private String name;
    private String observationType;
    private String status;
    private Long durationMs;
    private String provider;
    private String model;
    private Usage usage;
}

Save as src/main/java/com/metertrail/example/model/TraceData.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TraceData {
    private String name;
    private String status;
    private Long durationMs;
    private String userId;
    private String customerId;
    private String feature;
}

Save as src/main/java/com/metertrail/example/model/Usage.java

package com.metertrail.example.model;

import lombok.Getter;
import lombok.Setter;
import com.fasterxml.jackson.annotation.JsonInclude;

// Unknown usage must remain explicit null; it must not disappear from JSON.
@JsonInclude(JsonInclude.Include.ALWAYS)
@Getter
@Setter
public class Usage {
    private Long inputTokens;
    private Long outputTokens;
    private Long cachedInputTokens;
}
package com.metertrail.example;

import com.metertrail.example.model.Agent;
import com.metertrail.example.model.BatchReceipt;
import com.metertrail.example.model.BatchRequest;
import com.metertrail.example.model.Event;
import com.metertrail.example.model.ObservationData;
import com.metertrail.example.model.TraceData;
import com.metertrail.example.model.Usage;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

public class Send {
    public static void main(String[] args) throws Exception {
        Agent agent = new Agent();
        agent.setServiceName("document-api");
        agent.setEnvironment("test");
        agent.setInstanceId("demo-1");

        TraceData traceData = new TraceData();
        traceData.setName("Document analysis");
        traceData.setStatus("success");
        traceData.setDurationMs(2100L);
        traceData.setUserId("demo-user");
        traceData.setCustomerId("demo-customer");
        traceData.setFeature("document-analysis");

        Usage usage = new Usage();
        usage.setInputTokens(1500L);
        usage.setOutputTokens(400L);
        usage.setCachedInputTokens(0L); // Use null when unknown; 0 means no cache hits.

        ObservationData observationData = new ObservationData();
        observationData.setName("Model response");
        observationData.setObservationType("generation");
        observationData.setStatus("success");
        observationData.setDurationMs(2000L);
        observationData.setProvider("example");
        observationData.setModel("example-model");
        observationData.setUsage(usage);

        String traceId = UUID.randomUUID().toString().replace("-", "");
        String startedAt = Instant.now().toString(); // Replace with the measured request start.
        Event<TraceData> trace = new Event<>();
        trace.setEventId(UUID.randomUUID().toString());
        trace.setRevision(1L);
        trace.setType("trace");
        trace.setObjectId("trace-" + traceId);
        trace.setTraceId(traceId);
        trace.setStartedAt(startedAt);
        trace.setData(traceData);

        Event<ObservationData> observation = new Event<>();
        observation.setEventId(UUID.randomUUID().toString());
        observation.setRevision(1L);
        observation.setType("observation");
        observation.setObjectId("obs-" + traceId + "-1");
        observation.setTraceId(traceId);
        observation.setSpanId(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
        observation.setStartedAt(startedAt);
        observation.setData(observationData);

        BatchRequest batch = new BatchRequest();
        batch.setSchemaVersion("1.0");
        batch.setAgent(agent);
        batch.setEvents(List.of(trace, observation));

        MeterTrailClient client = new MeterTrailClient(
                requiredEnv("METERTRAIL_ENDPOINT"), requiredEnv("METERTRAIL_API_KEY"));
        // If retrying, reuse this batch unchanged, including every ID and timestamp.
        BatchReceipt receipt = client.sendBatch(batch);
        System.out.println("202 " + receipt.getStatus() + " batchId=" + receipt.getBatchId());
    }

    private static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) throw new IllegalArgumentException("Set " + name);
        return value;
    }
}
mvn -q compile exec:java

Run on your backend after the AI request finishes. Each run creates a trace and a model-call observation (2 units). Reuse the unchanged payload and IDs for retries. This example does not call a model or send prompt content.

4. Check the result

A successful upload returns HTTP 202. pending is a receipt for asynchronous processing, not a confirmation that data is already queryable.

{"batchId":"<batch-id>","received":2,"status":"pending"}

Optionally query the returned batchId using the same project key:

curl --fail-with-body --max-time 10 "https://metertrail.com/v1/batches/<batch-id>" \
  -H "Authorization: Bearer $METERTRAIL_API_KEY"

5. Find the trace in your console

Select the project associated with your key and open Traces. Refresh after processing and find Example request. Model cost can be Unknown because this minimal example does not report model usage or prices.

Troubleshooting

401: check the key and project. 400: check required fields and timestamps. For quota or subscription errors, check Billing. After a network timeout retry the same event IDs and content rather than creating new objects.

Full ingestion field reference

Other tutorials:

Track your first AI request with Node.js · Track your first AI request with Python · Integrate directly through the HTTP API