Search code examples
postmanslackslack-api

How to post a message with an image using Postman


I am trying send an image from POSTMAN. I am able to send a message but image is not getting posted.

https://slack.com/api/chat.postMessage

Used POST type headers i am passing token, channel and i have an Image URL but not sure how to send that. Can anyone please help me on this.


Solution

  • There are two alternative approaches on how to send your message to the API endpoint chat.postMessage:

    Body as form-urlencoded

    Here is how to include an image in a message send as x-www-form-urlencoded:

    The image has to be send as part of an attachment by setting the property called image_url.

    The attachments are set with the attachments key in the API call, which requires you define your attachments as array of attachment object in JSON.

    In addition to the image_url your attachment needs to contain a fallback property, which is used to display a text to the user in case the image can not be displayed.

    Your attachments object then looks like this in JSON:

    {
        "fallback": "this did not work",
        "image_url": "https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"
    }
    

    Now you have to put that into an array (by adding [] around it) and this is what you get as value for your attachments key:

    [{"fallback":"did not work","image_url":"https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"}]
    

    In addition you need to add the keys token, channel, text key to your message. Voila.

    Body as JSON

    An alternative and probably easier approach is to send your data as JSON instead of x-www-form-urlencoded to the API.

    This requires you to send the token in the Auth header and switch to JSON for the body.

    To do that in Postman put your token as "Bearer Token" under "Authorization". In "Body" switch to "raw" and select "JSON".

    Then you can define the whole message as follows:

    {
        "channel": "test",
        "text": "Hi there!",
        "attachments":
        [
            {
                "fallback": "this did not work",
                "image_url": "https://secure.gravatar.com/avatar/d6ada88a40de8504c6b6068db88266ad.jpg?s=512&d=https%3A%2F%2Fa.slack-edge.com%2F27b6e%2Fimg%2Favatars%2Fsmiley_blobs%2Fava_0016-512.png"
            }
    
        ]
    }
    

    Of course you can do the same in your code. Since your are working in JavaScript using JSON would be the natural approach.

    Note that not all API methods support sending the body in JSON. Check out this documentation for more info.