Search code examples
jsonvbams-word

Post JSON request in word VBA


How can I post a JSON request to a particular API while incorporating variables?


Solution

  • For this example, I posted to discord webhook.

    Dim objHTTP As Object
    Dim Json As String
    Json = "{""content"":""Howdy partner!"",""embeds"":null}"
    
    Dim result As String
    
    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "https://discord.com/api/webhooks/guildid/webhookid"
    objHTTP.Open "POST", URL, False
    
    objHTTP.setRequestHeader "Content-type", "application/json"
    objHTTP.send (Json)
    result = objHTTP.responseText
    
    Set objHTTP = Nothing
    

    Replace the URL with your URL and edit the JSON as you would like, but note JSON requires double quotes.

    Here is an example of incorporating variables into the json:

    Dim VARIABLE as String
    VARIABLE = "Howdy!"
    Json = "{""content"":""" & VARIABLE & """,""embeds"":null}"