How to: Call a web service and read its JSON response
Request data from a REST service in VBA and read fields of the JSON response.
Solution overview
MSXML2.ServerXMLHTTP.6.0 (part of Windows) sends the request; JDoc.LoadJson parses
responseText; the getters read the fields. LoadJson returning False and the HTTP status are
checked separately, because a service can answer an error with a body that is not JSON.
Implementation
Public Function GetCustomerName(ByVal customerId As Long) As String
Dim http As Object
Dim doc As New JDoc
Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.Open "GET", "https://api.example.com/customers/" & customerId, False
http.setRequestHeader "Accept", "application/json"
http.send
If http.Status <> 200 Then
Err.Raise vbObjectError + 1000, "GetCustomerName", "HTTP " & http.Status & ": " & http.statusText
End If
If Not doc.LoadJson(http.responseText) Then
Err.Raise vbObjectError + 1001, "GetCustomerName", _
"Invalid JSON in line " & doc.ParseError.Line & ": " & doc.ParseError.Reason
End If
GetCustomerName = doc.GetString("$.name", "")
End Function
To send JSON, build a document and pass its text:
Dim body As New JDoc body.SetValue "$.name", "Miller" body.SetValue "$.active", True http.Open "POST", "https://api.example.com/customers", False http.setRequestHeader "Content-Type", "application/json; charset=utf-8" http.send body.Json
Remarks
responseTextdecodes the body with the charset the server declares; services that send UTF-8 without declaring it may show wrong umlauts. Then decoderesponseBodywith anADODB.Stream(Charset = "utf-8") beforeLoadJson.- The synchronous call (
FalseinOpen) blocks Access until the service answers; sethttp.setTimeoutsfor slow services. - The URL above is an example; authentication headers depend on the service.
Related topics
en/wiki/msaccess/json/how-to/call-a-web-service.txt · Zadnja sprememba: uporabnika Wolfgang van der Stille