﻿---
title: Response types
description: The type argument of a call decides what you get back and what it costs: transport.Get<StringResponse>("/"), transport.PostAsync<JsonResponse>(...). Every...
url: https://docs-v3-preview.elastic.dev/elastic/elastic-transport-net/pull/313/response-types
products:
  - Elastic Transport .NET
  - Elasticsearch .NET Client
---

# Response types
The type argument of a call decides what you get back and what it costs: `transport.Get<StringResponse>("/")`, `transport.PostAsync<JsonResponse>(...)`. Every response type carries the details of the call in `ApiCallDetails` (status code, the nodes tried, the audit trail, timings), and the body in `Body`.

| Type                            | `Body`       | Use it for                                                                                                                                                                 |
|---------------------------------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`JsonResponse`](#jsonresponse) | `JsonNode`   | A quick look into a JSON response, one-off scripts and tools, anything without a class to deserialize into                                                                 |
| `StringResponse`                | `string`     | Small payloads, debugging, text that is not JSON                                                                                                                           |
| `BytesResponse`                 | `byte[]`     | Small binary payloads                                                                                                                                                      |
| `StreamResponse`                | `Stream`     | Large payloads. You must dispose the response                                                                                                                              |
| `PipeResponse`                  | `PipeReader` | .NET 10 and later. Large payloads, proxying and streaming, see [pipe streaming](https://docs-v3-preview.elastic.dev/elastic/elastic-transport-net/pull/313/pipe-streaming) |
| `VoidResponse`                  | none         | `HEAD`, and calls whose body you do not want. The body is not read                                                                                                         |
| `ElasticsearchJsonResponse`     | `JsonNode`   | `JsonResponse` with Elasticsearch error handling: `IsValidResponse`, `ElasticsearchServerError`, `ElasticsearchWarnings`                                                   |
| Your own `TransportResponse<T>` | `T`          | Typed deserialization, through a registered `IResponseBuilder`                                                                                                             |

All of them work with the native AOT and trimming: the repository's own `PublishAot` example (`examples/transport-aot-example`) is published as a native binary without warnings and exercises `JsonResponse`.

## JsonResponse

`JsonResponse` parses the body into a `System.Text.Json.Nodes.JsonNode` and reads a value from it by a path, so a one-off script does not need a class for the response, nor a chain of `["hits"]["hits"][0]["_source"]["title"]` with a null check at every step.
```csharp
var response = transport.Get<JsonResponse>("/my-index/_search?q=title:hello");

int total = response.Get<int>("hits.total.value");
string firstId = response.Get<string>("hits.hits.[0]._id");
string lastTitle = response.Get<string>("hits.hits.[last()]._source.title");
```

`Get<T>(path)` never throws for a path that is not there: it returns `default(T)` (`null`, `0`, `false`). That makes it safe to read from a response you know little about, and it means a missing value and a wrong path look alike. When it matters, read the node and check it.

### The path

A path is keys separated by dots. The segments are:

| Segment                | Reads                                                                                                                                                                                           |
|------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `name`                 | the property `name` of an object                                                                                                                                                                |
| `[0]`, or just `0`     | the item at that position of an array. A number on an object is the key of that name                                                                                                            |
| `[first()]`, `_first_` | the first item of an array                                                                                                                                                                      |
| `[last()]`, `_last_`   | the last item of an array                                                                                                                                                                       |
| `_arbitrary_key_`      | the value of the first property of an object, when you do not know its name (an index name in `GET /_mapping`, a node id in `GET /_nodes`). As the last segment it is the name of that property |
| `a\.b`                 | a key that has a dot in it: the dot is escaped with a backslash                                                                                                                                 |

```csharp
// the first hit's tags, the second one's
string tag = response.Get<string>("hits.hits.[0]._source.tags.[1]");

// the name of the index, and what its title is mapped as, whatever the index is called
var mappings = transport.Get<JsonResponse>("/my-*/_mapping");
string index = mappings.Get<string>("_arbitrary_key_");
string type = mappings.Get<string>("_arbitrary_key_.mappings.properties.title.type");

// a field whose name has dots in it
int value = response.Get<int>(@"hits.hits.[1]._source.meta.my\.dotted\.key");
```

A segment that does not fit what it reads from (`[0]` on an object, a name on an array, a position past the end, anything below a `null`) leads nowhere, and the whole path reads as the default.

### The type

`T` is what the value is converted to:

| `T`                                         | The value                                                                                                                       |
|---------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
| `string`                                    | a string as it is. A number or a bool is its JSON text (`7` is `"7"`). An object or an array is `null`: read it as a `JsonNode` |
| `int`, `long`, `float`, `double`, `decimal` | a number. `int` and `long` also read a string that holds an integer (`"42"`)                                                    |
| `bool`                                      | `true` or `false`                                                                                                               |
| `DateTime`, `DateTimeOffset`, `Guid`        | a JSON string in the usual format                                                                                               |
| `JsonNode` or `object`                      | the node itself, for an object or an array, or to look further: `response.Get<JsonNode>("hits.hits")`                           |

A value that is not the type you ask for (a word read as an `int`) is the default, not an exception.

### The DOM

`Body` is the `JsonNode`, so everything `System.Text.Json.Nodes` does is there when a path is not enough:
```csharp
foreach (var hit in response.Get<JsonNode>("hits.hits")!.AsArray())
    Console.WriteLine($"{hit!["_id"]}: {hit["_source"]!["title"]}");

string title = response.Body!["hits"]!["hits"]![0]!["_source"]!["title"]!.GetValue<string>();
```

A response whose content type is not JSON holds the text under a single property, `body`: `response.Get<string>("body")`.

### Elasticsearch

`ElasticsearchJsonResponse` reads the same paths. It adds what the Elasticsearch product knows: a failed request has its error parsed (`ElasticsearchServerError`), `IsValidResponse` says whether it succeeded, and the warnings of the server are in `ElasticsearchWarnings`.
```csharp
var response = await transport.GetAsync<ElasticsearchJsonResponse>("/_cluster/health");
if (!response.IsValidResponse)
    Console.WriteLine(response.ElasticsearchServerError);
Console.WriteLine(response.Get<string>("status"));
```


## StringResponse and BytesResponse

The body, read whole. `StringResponse` for text and for printing what came back, `BytesResponse` for bytes. Neither parses anything, so neither fails on content that is not JSON. When the call fails, the bytes the server sent are kept in `ApiCallDetails.ResponseBodyInBytes`, whatever its content type, so an error page from a proxy can be read as well.
```csharp
var response = await transport.GetAsync<StringResponse>("/_cat/indices?v");
Console.WriteLine(response.Body);
```


## VoidResponse

For a call whose result is its status: `HEAD`, or a call you fire and do not read. The body is not read, so nothing is allocated for it.
```csharp
var exists = (await transport.HeadAsync("/my-index")).ApiCallDetails.HasSuccessfulStatusCode;
```


## StreamResponse and PipeResponse

The body is not read until you do, which suits a large one: it goes from the socket to wherever you send it without being held in memory. You **must** dispose the response, which releases the connection.
```csharp
await using var response = await transport.GetAsync<StreamResponse>("/my-index/_search");
await response.Body.CopyToAsync(destination);
```

`PipeResponse` is the same on .NET 10 and later, with a `PipeReader`. See [pipe streaming](https://docs-v3-preview.elastic.dev/elastic/elastic-transport-net/pull/313/pipe-streaming).

## A response of your own

A response with a type of its own is a class that derives from `TransportResponse<T>`, and an `IResponseBuilder` that builds it from the stream, registered with the product registration or the response factory. The response types above are built the same way, and `TypedResponseBuilder<TResponse>` is the place to start.

## The audit trail and the details of the call

Whatever the type, `response.ApiCallDetails` says what happened: `HttpStatusCode`, `HasSuccessfulStatusCode`, `DebugInformation`, and the `AuditTrail` with an entry for each node asked and what it answered. The same goes for a request that failed: with `ThrowExceptions` off the response is there, with the reason in `ApiCallDetails`. See [the request pipeline](https://docs-v3-preview.elastic.dev/elastic/elastic-transport-net/pull/313/request-pipeline) for what the trail means.