Home > OS >  Microsoft Graph sending chat message with fetch() BadRequest
Microsoft Graph sending chat message with fetch() BadRequest

Time:07-26

According to the graph API (https://docs.microsoft.com/en-us/graph/api/chat-post-messages), this is the form for POSTing a chat message.

POST https://graph.microsoft.com/v1.0/chats/19:[email protected]/messages
Content-type: application/json

{
  "body": {
     "content": "Hello world"
  }
}

However, when I make the following fetch request, the returned JSON indicates the body is malformed. Exact ID & token redacted.

fetch("https://graph.microsoft.com/v1.0/chats/{CHAT-ID}/messages",
    {
        method: "POST",
            headers: {
                "Authorization": "Bearer {ACCESS-TOKEN}",
                "Host": "graph.microsoft.com",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ "content": "Message" })
    })
    .then(response => response.json())
    .then(res => {
        console.log(res);
    })
{
  error: {
    code: 'BadRequest',
    message: 'Missing body content',

...

Thanks for any help!

CodePudding user response:

You are missing body property in your request. The body in this case is a property of chatMessage resource.

Try to change JSON.stringify({ "content": "Message" }) to JSON.stringify({"body": { "content": "Message" }}) it will ensure that the request body will have the correct structure.

fetch("https://graph.microsoft.com/v1.0/chats/{CHAT-ID}/messages",
    {
        method: "POST",
            headers: {
                "Authorization": "Bearer {ACCESS-TOKEN}",
                "Host": "graph.microsoft.com",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({"body": { "content": "Message" }})
    })
    .then(response => response.json())
    .then(res => {
        console.log(res);
    })
  • Related