> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Messages

> Get messages or conversations for Facebook, Instagram, X/Twitter, or WhatsApp, with filters for status, conversationId, and limit, plus caching details.

> [!NOTE]
>
> **Targeting X/Twitter?** Starting March 31, 2026, all X operations require your own API credentials. After linking X via OAuth, include these 2 headers in your request:
>
> `X-Twitter-OAuth1-Api-Key` — Your API Key (Consumer Key)
>
> `X-Twitter-OAuth1-Api-Secret` — Your API Key Secret (Consumer Secret)
>
> **One-time setup per Ayrshare account.** You create one X Developer App and reuse the same API Key and Secret across every sub-profile / end-user you link. You do *not* create a new app per customer.
>
> Not linked yet? See the [full setup guide](https://www.ayrshare.com/docs/dashboard/connect-social-accounts/x-twitter-byo-keys.md) to connect your X account.
>
> Your keys are never logged or stored by Ayrshare.

Get messages or conversations for a messaging platform.

Retrieval times differ on each social network. On Facebook, Instagram, and WhatsApp, messages are available via Ayrshare in real time. On X/Twitter, there is a delay of up to 3 minutes to see new message updates. Please contact support to learn more about the Enterprise Plan if you need real-time X/Twitter message access.

> [!NOTE]
>
> **Response caching:** For **Facebook** and **Instagram**, responses are cached for **60
> seconds**. For **X/Twitter**, responses are cached for **15 seconds** to better support polling.
> WhatsApp reads messages already received through Meta webhooks, so a newly received message can
> appear as soon as Ayrshare processes its webhook. The response still includes `lastUpdated` and
> `nextUpdate` metadata.

> [!NOTE]
>
> Initial message history retrieval for Facebook and Instagram is limited to the
> last 20 messages. Please see the [Message History Retrieval for Facebook and
> Instagram](https://www.ayrshare.com/docs/apis/messages/overview.md#message-history-retrieval-for-facebook-and-instagram)
> section for more information.

> [!NOTE]
>
> WhatsApp conversations are identified by the correspondent's phone number
> (digits only, E.164 without the leading `+`). A stored outbound message may include a `status`
> value of `sent`, `delivered`, `read`, or `failed`.

> [!NOTE]
>
> WhatsApp messages sent through [Send Message](https://www.ayrshare.com/docs/apis/messages/send-message.md) are not currently
> added to Get Messages history. Incoming WhatsApp messages received through webhooks are stored
> and returned here.

## Header Parameters

**Authorization** `string` *required*

[API Key](https://www.ayrshare.com/docs/apis/overview.md#authorization) of the Primary Profile.

Format: `Authorization: Bearer API_KEY`
**Profile-Key** `string`

[Profile Key](https://www.ayrshare.com/docs/apis/overview.md#profile-key-format) of a User Profile.

Format: `Profile-Key: PROFILE_KEY`

## Path Parameters

**platform** `string` *required*

The platform to get the message: `facebook`, `instagram`, `twitter`, `whatsapp`

## Query Parameters

**status** `string` *required* (default: active)

Return active conversations or archived conversations. Values: `active` or `archived`.

**conversationId** `string`

Only return the specific conversation.

**action** `string`

Only return messages in one direction. Values: `sent` or `received`. Omit to
return both.

**conversationsOnly** `boolean` (default: false)

Return conversations instead of messages. Returns one page of conversations — follow `meta.pagination.next` for the rest. If `true`, `conversationId` is ignored.

> [!NOTE]
>
> When `conversationsOnly=true`, conversation details are returned in
> `converstationsDetails`. This spelling is part of the current API response.

**limit** `integer`

Page size for messages and for conversation lists: an integer from 1 to 100,
with a default and maximum of **100**.

On X/Twitter `limit` also chooses which set of messages you read. Omit it to
page your stored messages, which is what every other platform does and what
applies `status`, `action` and `conversationsOnly`. Supply it to page X's live
timeline through X's own cursor instead, which applies none of those three
filters.

That choice is made by the **first** request only. Once you are following a
cursor, the cursor decides: a stored cursor keeps returning stored messages
even if you send `limit`, and an X cursor keeps returning the live timeline
even if you omit it. You cannot switch between the two mid-pagination.

**next** `string`

Opaque cursor from `meta.pagination.next`. Pass it as `next` with the same
profile, platform and filters. Continue while `meta.pagination.hasMore` is
`true`, even if a filtered page comes back short or empty. `limit` may be
omitted on subsequent requests and defaults to 100; on X/Twitter the cursor
already records which set of messages it came from, so sending or omitting
`limit` alongside it will not switch you to the other one.

### Fetching the next page

Start with `GET /api/messages/instagram?limit=100`. To continue, URL-encode the
returned `meta.pagination.next` value and send
`GET /api/messages/instagram?limit=100&next=<opaque cursor>`. The parameter is
`next`, not `cursor`. Keep the same Profile-Key and query filters throughout.

Check `meta.pagination.hasMore`, not the number of results, to decide when to
stop. A filtered request may return fewer than `limit` results, or an empty page
with a continuation, because each request scans a bounded portion of history.
Messages in stored history are ordered newest first, with document ID breaking
ties. Conversation lists are ordered by document ID. Paging is not a frozen
snapshot: new messages appear when you restart from the first page, and changing
conversation statuses can change filtered results.

Existing message fields and the `converstationsDetails` spelling are unchanged.
Integrations that previously expected a complete list from one request — whether
of messages or of conversations, on any platform — must follow the continuation
cursor; increasing `limit` above 100 is not supported.

```bash cURL theme={"system"}
curl \
-H "Authorization: Bearer API_KEY" \
-X GET https://api.ayrshare.com/api/messages/facebook
```

```javascript JavaScript theme={"system"}
const apiKey = 'API_KEY';
const url = 'https://api.ayrshare.com/api/messages/facebook';

const headers = {
  'Authorization': `Bearer ${apiKey}`,
};

fetch(url, {
  method: 'GET',
  headers: headers,
})
  .then(response => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error(`Request failed. Status code: ${response.status}`);
    }
  })
  .then(data => {
    console.log('Response:', data);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });
```

```python Python theme={"system"}
import requests

api_key = 'API_KEY'
url = 'https://api.ayrshare.com/api/messages/facebook'

headers = {
    'Authorization': f'Bearer {api_key}',
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    data = response.json()
    print('Response:', data)
else:
    print(f'Request failed. Status code: {response.status_code}')
```

```php PHP theme={"system"}
<?php

$apiKey = 'API_KEY';
$url = 'https://api.ayrshare.com/api/messages/facebook';

$headers = [
    'Authorization: Bearer ' . $apiKey,
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    echo 'Error: ' . $error;
} else {
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($statusCode === 200) {
        $responseData = json_decode($response, true);
        print_r($responseData);
    } else {
        echo 'Request failed. Status code: ' . $statusCode;
    }
}

curl_close($ch);

?>
```

```csharp C# theme={"system"}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        string apiKey = "API_KEY";
        string url = "https://api.ayrshare.com/api/messages/facebook";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

        try
        {
            var response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
                var responseData = JsonSerializer.Deserialize<dynamic>(responseBody);

                Console.WriteLine("Response:");
                Console.WriteLine(responseData);
            }
            else
            {
                Console.WriteLine($"Request failed. Status code: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}
```

```java Java theme={"system"}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) {
        String apiKey = "API_KEY";
        String url = "https://api.ayrshare.com/api/messages/facebook";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .GET()
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                String responseBody = response.body();
                System.out.println("Response:");
                System.out.println(responseBody);
            } else {
                System.out.println("Request failed. Status code: " + response.statusCode());
            }
        } catch (IOException | InterruptedException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
```

```json 200: Success theme={"system"}
{
    "status": "success",
    "messages": [
        {
            "senderId": "106638148652444",
            "senderDetails": {
                "name": "Ayrshare"
            },
            "conversationId": "t_10161117434308444",
            "created": "2024-06-06T00:54:32.455Z",
            "action": "sent",
            "recipientId": "7101149746568444",
            "id": "m_JH6o-yS83JoxWmQaLrmgSaHwGtfTgQ",
            "message": "Howdy!",
            "platform": "facebook",
            "reactions": {
                "7101149746568522": "😆". // Reaction by the customer on the Howdy! message
            }
        },
        {
            "recipientDetails": {
                "name": "Sara Smith",
                "id": "736532028017333",
                "picture": "https://img.ayrshare.com/333/messages/facebook-eTZzhE2b.jpeg"
            },
            "senderId": "106638148652329",
            "attachments": [
                {
                    "type": "image",
                    "url": "https://scontent.xx.fbcdn.net/v/t1.15752-9/490986808_1193328359195158"
                }
            ],
            "conversationId": "t_3567590438533",
            "created": "2024-06-06T00:54:32.455Z",
            "action": "sent",
            "recipientId": "736532028017333",
            "id": "m_WJlfgzopxfdRM1wFTKYHKv7zh75P",
            "updated": "2024-06-06T00:54:32.455Z",
            "platform": "facebook",
            "senderDetails": {
                "name": "Ayrshare"
            }
        },
        {
            "senderId": "7101149746568444",
            "senderDetails": {
                "name": "John Smith",
                "profileImage": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
            },
            "conversationId": "t_10161117434308444",
            "created": "2024-06-06T00:54:28.102Z",
            "action": "received",
            "recipientId": "106638148652329",
            "id": "m_HGbotYJUmf4AzyPlJ-2uZqHwGtfTgQihX",
            "message": "Look up!",
            "platform": "facebook"
        },
        {
            "senderId": "7101149746568444",
            "senderDetails": {
                "name": "John Smith",
                "profileImage": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
            },
            "conversationId": "t_10161117434308444",
            "created": "2024-06-06T00:49:11.679Z",
            "action": "received",
            "recipientId": "106638148652444",
            "id": "m_jXoYQIwTXaq2u06PG6Z8vaHwGtfTgQ",
            "message": "How is the weather?",
            "platform": "facebook"
        }
    ],
    "lastUpdated": "2024-06-09T21:46:04.233Z",
    "nextUpdate": "2024-06-09T21:47:04.233Z"
}
```

```json 200: Paginated (X/Twitter) theme={"system"}
{
    "status": "success",
    "messages": [
        {
            "id": "1893410668991234567",
            "conversationId": "1234567890-9876543210",
            "senderId": "9876543210",
            "created": "2024-06-09T21:30:00.000Z",
            "message": "Hey, how are you?",
            "action": "received",
            "senderDetails": {
                "name": "Jane Doe",
                "username": "janedoe"
            }
        },
        {
            "id": "1893410668991234566",
            "conversationId": "1234567890-9876543210",
            "senderId": "1234567890",
            "created": "2024-06-09T21:28:00.000Z",
            "message": "Hello!",
            "action": "sent",
            "senderDetails": {
                "name": "My Account",
                "username": "myaccount"
            }
        }
    ],
    "messagesCount": 2,
    "lastUpdated": "2024-06-09T21:46:04.233Z",
    "nextUpdate": "2024-06-09T21:46:19.233Z",
    "meta": {
        "pagination": {
            "hasMore": true,
            "limit": 5,
            "next": "eyJwYWdpbmF0aW9uVG9rZW4iOiIxODkzNDEwNjY4OTkxMjM0NTY1In0="
        }
    }
}
```

```json 200: WhatsApp theme={"system"}
{
  "status": "success",
  "messages": [
    {
      "id": "wamid.HBgLMTQxNTU1NTEyMzQVAgARGBI3MEM3Q0NDQjlGRTUzMjJBNEUA",
      "conversationId": "14155551234",
      "senderId": "14155551234",
      "recipientId": "123456789012345",
      "created": "2026-05-18T17:10:02.000Z",
      "message": "When is my order shipping?",
      "action": "received",
      "platform": "whatsapp"
    },
    {
      "id": "wamid.HBgLMTQxNTU1NTEyMzQVAgARGBI4OUYxRkExNzE0M0EwQTYwM0EA",
      "conversationId": "14155551234",
      "senderId": "14155551234",
      "recipientId": "123456789012345",
      "created": "2026-05-18T17:08:41.000Z",
      "attachments": [
        {
          "type": "image",
          "url": "https://img.ayrshare.com/abc123/whatsapp/whatsapp_image_x9aB2pK7.jpg"
        }
      ],
      "action": "received",
      "platform": "whatsapp"
    }
  ],
  "lastUpdated": "2026-05-18T17:13:00.000Z",
  "nextUpdate": "2026-05-18T17:14:00.000Z"
}
```

```json 200: WhatsApp Conversations theme={"system"}
{
  "status": "success",
  "conversationIds": ["14155551234", "447700900123"],
  "converstationsDetails": [
    {
      "id": "14155551234",
      "participant": {
        "id": "14155551234",
        "name": "Jane Customer"
      },
      "status": "active",
      "unread": 2
    },
    {
      "id": "447700900123",
      "participant": {
        "id": "447700900123"
      },
      "status": "active",
      "unread": 0
    }
  ],
  "lastUpdated": "2026-05-18T17:13:00.000Z",
  "nextUpdate": "2026-05-18T17:14:00.000Z"
}
```

```json 200: Conversations theme={"system"}
{
  "status": "success",
  "conversationIds": ["t_10161117434308444", "t_356759043857444"],
  "converstationsDetails": [
    {
      "id": "t_10161117434308444",
      "participant": {
        "name": "John Smith",
        "id": "7101149746568444",
        "picture": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
      },
      "status": "active",
      "watermark": 1717889607444
    },
    {
      "id": "t_356759043857444",
      "participant": {
        "name": "Sara Johnson",
        "id": "7365320280173444",
        "picture": "https://platform-lookaside.fbsbx.com/platform/profilepic/"
      },
      "status": "active"
    }
  ],
  "lastUpdated": "2024-06-09T21:46:04.233Z",
  "nextUpdate": "2024-06-09T21:47:04.233Z"
}
```

```json 403: Messaging Not Enabled theme={"system"}
{
  "action": "messages",
  "status": "error",
  "code": 361,
  "message": "Messaging is not enabled for this User Profile. Please subscribe to Messaging and activate Messaging for this User Profile."
}
```

```json 400: Social Account Needs Relinking theme={"system"}
{
  "action": "messages",
  "status": "error",
  "code": 362,
  "message": "The social network needs to be relinked to access Messaging. Please unlink, relink, and try again.",
  "resolution": {
    "relink": true,
    "platform": "facebook"
  }
}
```

```json 403: X App Missing Direct Message Permission theme={"system"}
{
  "action": "messages",
  "status": "error",
  "code": 520,
  "message": "X rejected this request because the linked X app does not have Direct Message permission. In the X Developer Portal, set the User authentication settings for the app to \"Read and write and Direct messages\", then unlink and relink the X account. X tokens keep the permissions they were created with, so changing the app setting alone is not enough.",
  "resolution": {
    "relink": true,
    "platform": "twitter"
  }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.