# Return all threads

> **GET** `https://api.us.nylas.com/v3/grants/{grant_id}/threads`

Source: https://developer.nylas.com/docs/reference/api/threads/get-threads/

Returns all threads.

For Microsoft, IMAP, iCloud, Yahoo, and EWS, threads are ordered reverse chronologically by the latest message received.

For Google, thread ordering is not guaranteed to be reverse chronological due to a Gmail API limitation.
However, setting the `in` query parameter improves the likelihood of reverse chronological ordering significantly (approximately 40%).
While reverse chronological ordering remains unguaranteed even with the `in` parameter, we recommend using it to increase the chance of this ordering pattern.

<div id="admonition-warning">
⚠️ <b>Your users might receive a large number of threaded messages</b>. If you encounter
<a href="/docs/api/errors/400-response/"><code>429</code> errors</a> or provider
<a href="/docs/dev-guide/platform/rate-limits/">rate limits</a> when listing all threads, Nylas
recommends you set the <code>limit</code> parameter to 20 and add
<a href="#query-parameters">query parameters</a> to your request to
limit the results.</div>

**Authentication:** NYLAS_API_KEY, ACCESS_TOKEN

## Parameters

### Query parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `any_email` | string | No | Filter for threads that contain messages sent to or received from the email addresses in the comma-separated list. You may specify a maximum of 25 email addresses per query. |
| `bcc` | string | No | Filter for threads that contain messages BCC'd to the specified email address. Because most SMTP gateways remove BCC information from sent messages, any messages that Nylas returns are likely sent from the parent account.  For Microsoft grants, Nylas sometimes doesn't return messages that satisfy the conditions of this query parameter. This is because of a limitation on the provider. Instead, you can use the `thread_id` to retrieve a specific conversation. |
| `cc` | string | No | Filter for threads that contain messages CC'd to the specified email address.  For Microsoft grants, Nylas sometimes doesn't return messages that satisfy the conditions of this query parameter. This is because of a limitation on the provider. Instead, you can use the `thread_id` to retrieve a specific conversation. |
| `from` | string | No | Filter for threads that include messages sent from the specified email address. If you want to filter for threads that include messages sent from the current grant, use the `in` query parameter and specify the Sent folder instead.  For Microsoft grants, Nylas sometimes doesn't return messages that satisfy the conditions of this query parameter. This is because of a limitation on the provider. Instead, you can use the `thread_id` to retrieve a specific conversation. |
| `has_attachment` | boolean | No | When `true`, filters for threads that include attachments. |
| `in` | string | No | Return messages in the specified folder or label, by folder ID. Required when using `shared_from`. |
| `earliest_message_date` | integer | No | Returns the date when the earliest or first message in the thread was sent or received, in Unix  timestamp format. |
| `latest_message_after` | integer | No | Filter for threads whose most recent message was received after the specified time, in Unix timestamp format. |
| `latest_message_before` | integer | No | Filter for threads whose most recent message was received before the specified time, in Unix timestamp format. |
| `limit` | integer | No | The maximum number of objects to return. See [pagination](/docs/reference/api/#pagination) for more information. |
| `page_token` | string | No | An identifier that specifies which page of data to return. You can get this value from the `next_cursor` response field. See [Pagination](/docs/reference/api/#pagination) for more information. |
| `search_query_native` | string | No | Specify a URL-encoded provider-specific query string. Each provider supports a limited set of query parameters that you can use in your request alongside `search_query_native`:  - **Google**: `in`, `limit`, and `page_token` - **Microsoft**: `in`, `limit`, and `page_token` - **IMAP/Yahoo/iCloud**: Any parameter - **EWS**: Any parameter _except_ `thread_id`  For more information, see [Searching with Nylas](/docs/dev-guide/best-practices/search/#search-messages-and-threads-using-search_query_native). |
| `select` | string | No | Specify fields that you want Nylas to return, as a comma-separated list (for example, `select=id,updated_at`). This allows you to receive only the portion of object data that you're interested in. You can use `select` to optimize response size and reduce latency by limiting queries to only the information that you need. |
| `shared_folder_id` | string | No | (Microsoft only) When provided, Nylas returns items from the specified shared folder ID. Required when using `shared_from`. This parameter only accepts a single folder ID. Check out the [Shared folders](/docs/provider-guides/microsoft/shared-folders) guide for more information. |
| `shared_from` | string | No | (Microsoft only) When provided, Nylas returns items that were shared from the specified email address. It also accepts grant ID. This parameter only accepts single email address or grant ID. Check out the [Shared folders](/docs/provider-guides/microsoft/shared-folders) guide for more information. |
| `starred` | boolean | No | Filter for threads that contain one or more starred messages. |
| `subject` | string | No | Return threads that contain messages with a matching subject. This filter is case-sensitive and returns partial matches. |
| `to` | string | No | Filter for threads that contain messages sent to the specified email address.  For Microsoft grants, Nylas sometimes doesn't return messages that satisfy the conditions of this query parameter. This is because of a limitation on the provider. Instead, you can use the `thread_id` to retrieve a specific conversation. |
| `unread` | boolean | No | Filter for threads that contain one or more unread messages. |

### Path parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `grant_id` | string | Yes | ID of the grant to access. You can also use the email address associated with the grant, or use `/me/` to refer to the grant associated with an access token. |

## Responses

### 200 - Threads response

- `request_id` (string) - The request ID.
- `data` (object)
  - `threads` (array)
    - `grant_id` (string) - The ID of grant for the connected user.
    - `id` (string) - A globally unique object identifier for Microsoft accounts. An email address for Google accounts.
    - `object` (string) - The type of object (in this case, `thread`).
    - `latest_draft_or_message` (object) - The latest message or draft in the thread.
      - `attachments` (array) - An array of Attachment objects. For Google, linked Google Drive files are not included. For
Microsoft, linked OneDrive files are not included.
        - `id` (string) **(required)** - The ID of the attachment.
        - `content_type` (string) - The [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types) of the attachment, used by the email client to determine how to display the attachment. If you don't provide a type, Nylas infers it from the file name.
The value of this field is exactly the same as the email attachment's `Content-Type` header.
The provider might set additional parameters, such as `name` and `charset`.

Nylas returns an empty `content_type` field if an attachment file name contains non-ASCII characters (for example, accented characters like `ü`). This is because Google can't detect its content type.
        - `filename` (string) - The file name of the attachment.
        - `grant_id` (string) - The ID of grant for the connected user.
        - `content_id` (string) - (Inline attachments only) The alphanumeric `cid` from the `<img>` tag in the message's HTML. For
example, you might see something like `<img src=\"cid:ce9b9547-9eeb-43b2-ac4e-58768bdf04e4\">` in
the message body.

Sometimes, the `content_id` value is contained in angle brackets (for example,
`<ce9b9547-9eeb-43b2-ac4e-58768bdf04e4>`).
        - `content_disposition` (string) - (Not supported for Microsoft and EWS) The content disposition of the attachment. Usually, this is `inline` or `attachment` followed by the file name (for example, `inline; filename="some-image.jpeg"`).
        - `is_inline` (boolean) - If `true`, indicates that the attachment is an inline file.
        - `size` (integer) - The size of the attachment, in bytes.
      - `bcc` (array) - An array of name/email address pairs that the message was BCC'd to. For received messages, this
is nearly always empty.
        - `name` (string)
        - `email` (string) **(required)**
      - `body` (string) - The body of the message as either plain-text or HTML content. If the message has both plain-text
and HTML, Nylas returns the HTML version.
      - `cc` (array) - An array of name/email address pairs that the message was CC'd to.
        - `name` (string)
        - `email` (string) **(required)**
      - `date` (integer) - Unix timestamp in seconds that represents when _the mail server_ received the message. This might be
different from the unified `Date` header in a raw Message object.
      - `folders` (array) - The IDs of the folders that the message appears in. Microsoft messages can be in a single folder
only. Google allows a single message to appear in multiple folders.
      - `from` (array) - A list of name/email address pairs that the message was sent from. This is usually one pair only,
but can be many.
        - `name` (string)
        - `email` (string)
      - `grant_id` (string) - The ID of grant for the connected user.
      - `headers` (array) - An array of key-value pairs that contain the message headers. Nylas returns this field when you
set the `fields` query parameter to either `include_headers` or `include_basic_headers`.

- `fields=include_headers`: Returns the full set of headers on the message.
- `fields=include_basic_headers`: Returns only the three RFC threading headers (`Message-ID`,
  `In-Reply-To`, `References`). Use this option when you only need to track message identity and
  thread relationships — payload size is significantly smaller than `include_headers`.

A single message can sometimes have multiple headers with the same key name. Nylas adds all of
the headers to the `headers` array without merging or de-duplicating the data. When the headers
contain encoded data, Nylas adds it to the `headers` array without decoding it. If you need the
decoded data, you need to build decoding logic into your project.

Some headers might contain raw MIME information (for example,
`=?Windows-1252?Q?Re:_Candidature_de_Mme_Leyah_Miller?=`).
        - `name` (string) **(required)**
        - `value` (string) **(required)**
      - `id` (string) - A globally unique object identifier for Microsoft accounts. An email address for Google accounts.
      - `in_reply_to` (string) - (EWS only) The ID of the message that this message replies to. This ID is the same as the
`In-Reply-To` header.
      - `metadata` (object) - The metadata associated with the object. For more information, see
[Metadata](/docs/reference/api/#metadata).
      - `object` (string) - The object type of the response (in this case, `message`).
      - `raw_mime` (string) - A Base64url-encoded string containing the message data (including the body content).

To get the raw MIME content for a message, set the `fields` query parameter to `raw_mime` in
your request. When you request raw MIME data, Nylas returns the `grant_id`, `object`, `id`,
and `raw_mime` fields only.
      - `reply_to` (array) - An array of name/email address pairs that should receive replies to the message.
        - `name` (string)
        - `email` (string) **(required)**
      - `snippet` (string) - A short snippet (the first 100 characters, with HTML tags removed) of the message body. This is
useful for displaying a preview of the message.
      - `starred` (boolean) - If `true`, shows that the message has been starred by the user. For EWS, this is only supported
on Microsoft Exchange 2010 or later.
      - `subject` (string) - The subject of the message.
      - `thread_id` (string) - A reference to the parent Thread object. Every message is associated with a thread, whether that
thread contains one message or many. If the message is new, Nylas assigns a `thread_id` to it.
      - `to` (array) - An array of name/email address pairs that the message was sent to.
        - `name` (string)
        - `email` (string) **(required)**
      - `tracking_options` (object) - Tracking options for the message.
        - `opens` (boolean) - When `true`, shows that message open tracking is enabled.
        - `thread_replies` (boolean) - When `true`, shows that thread replied tracking is enabled.
        - `links` (boolean) - When `true`, shows that link clicked tracking is enabled.
        - `label` (string) - A label describing the message tracking purpose.
      - `unread` (boolean) - If `true`, shows that the message has not been read by the user.
    - `has_attachments` (boolean) - When `true`, indicates that the message has attachments.
    - `has_drafts` (boolean) - When `true`, indicates that the message is a draft.
    - `earliest_message_date` (integer) - The date when the earliest or first message in the thread was sent or received, in seconds using the Unix timestamp
format.
    - `latest_message_received_date` (integer) - The date when the most recent incoming message in the thread was received, in seconds using the Unix timestamp
format.
    - `latest_message_sent_date` (integer) - The date when the most recent outgoing message in the thread was sent, in seconds using the Unix timestamp format.
    - `participants` (array) - A sub-object that contains the names and email addresses of all participants in the thread.
      - `email` (string)
      - `name` (string)
    - `snippet` (string) - A short snippet (the first 100 characters, with HTML tags removed) of the body of the last
received message. This is useful for displaying a preview of a message.
    - `starred` (boolean) - When `true`, indicates that the thread is starred. For EWS, this is only supported for Microsoft
Exchange 2010 or later.
    - `subject` (string) - The subject line of the thread.
    - `unread` (boolean) - When `false`, indicates that all messages in the thread have been read.
    - `message_ids` (array) - An array of IDs for all messages in the thread.
    - `draft_ids` (array) - An array of IDs for all drafts in the thread.
    - `folders` (array) - An array of folder IDs for all folders that the messages in the thread appear in.

Microsoft messages can only be in one folder at a time. Google messages can be in multiple
folders.
- `next_cursor` (string,null) - A cursor pointing to the next page of results for the request.

### 400 - Bad Request

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.
  - `provider_error` (object) - The error from the provider.

### 401 - Unauthorized

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.
  - `provider_error` (object) - The error from the provider.

### 429 - Rate Limit

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.

### 504 - Provider Failure

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.

## Code samples

### cURL

```bash
curl --compressed --request GET \
  --url "https://api.us.nylas.com/v3/grants/<NYLAS_GRANT_ID>/threads?limit=5" \
  --header 'Accept: application/json' \
  --header 'Authorization: Bearer <NYLAS_API_KEY>' \
  --header 'Content-Type: application/json'
```

### Node.js SDK

```javascript
import Nylas from "nylas";

const nylas = new Nylas({
  apiKey: "<NYLAS_API_KEY>",
  apiUri: "<NYLAS_API_URI>",
});

async function fetchRecentThreads() {
  try {
    const identifier = "<NYLAS_GRANT_ID>";
    const threads = await nylas.threads.list({
      identifier: identifier,
      queryParams: {
        limit: 5,
      },
    });

    console.log("Recent Threads:", threads);
  } catch (error) {
    console.error("Error fetching threads:", error);
  }
}

fetchRecentThreads();

```

### Python SDK

```python
from nylas import Client

nylas = Client(
    "<NYLAS_API_KEY>",
    "<NYLAS_API_URI>"
)

grant_id = "<NYLAS_GRANT_ID>"

threads = nylas.threads.list(
  grant_id,
  query_params={
    "limit": 5
  }
)

print(threads)
```

### Ruby SDK

```ruby
require 'nylas'

nylas = Nylas::Client.new(api_key: "<NYLAS_API_KEY>")
query_params = { limit: 5 }
threads, _ = nylas.threads.list(identifier: "<NYLAS_GRANT_ID>", query_params: query_params)

threads.map.with_index { |thread, i|
  puts("Thread #{i}")
  participants = thread[:participants]

  participants.each{ |participant|
    puts(
      "Subject: #{thread[:subject]} | "\
      "Participant: #{participant[:name]} | "\
      "Email: #{participant[:email]}"
    )
  }
}
```

### Java SDK

```java
import com.nylas.NylasClient;
import com.nylas.models.*;
import com.nylas.models.Thread;
import java.util.List;

public class ReadThreadParameters {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

    ListThreadsQueryParams queryParams = new ListThreadsQueryParams.Builder().limit(5).build();
    ListResponse<Thread> threads = nylas.threads().list("<NYLAS_GRANT_ID>", queryParams);
    int index = 0;

    for(Thread thread : threads.getData()){
      System.out.printf("%s ", index);

      List<EmailName> participants = thread.getParticipants();
      assert participants != null;

      for(EmailName participant : participants){
        System.out.printf("  Subject: %s | Participant: %s | Email: %s%n",
            thread.getSubject(),
            participant.getName(),
            participant.getEmail());
      }
      
      index++;
    }
  }
}
```

### Kotlin SDK

```kotlin
import com.nylas.NylasClient
import com.nylas.models.*
import java.util.*

fun main(args: Array<String>) {
  val nylas: NylasClient = NylasClient(
      apiKey = "<NYLAS_API_KEY>"
  )

  val queryParams = ListThreadsQueryParams(limit = 5)
  val threads : List<Thread> = nylas.threads().list("<CALENDAR_ID>", queryParams).data

  for(i in threads.indices){
    print("$i ")

    val participants = threads[i].participants

    if (participants != null) {
      for(participant in participants){
        println(" Subject: ${threads[i].subject} + " +
            "Name: ${participant.name} + " +
            "Email: ${participant.email}")
      }
    }
  }
}
```
