VBA-Web makes working with complex webservices and APIs easy with VBA on Windows and Mac. It includes support for authentication, automatically converting and parsing JSON, working with cookies and headers, and much more.
- Download the latest release (v4.0.0-rc.5)
- To install/upgrade in an existing file, use
VBA-Web - Installer.xlsm - To start from scratch on Excel,
VBA-Web - Blank.xlsmhas everything setup and ready to go
For more details see the Wiki
The following examples demonstrate using the Google Maps API to get directions between two locations.
Function GetDirections(Origin As String, Destination As String) As String
' Create a RestClient for executing requests
' and set a base url that all requests will be appended to
Dim MapsClient As New RestClient
MapsClient.BaseUrl = "https://maps.googleapis.com/maps/api/"
' Use GetJSON helper to execute simple request and work with response
Dim Resource As String
Dim Response As RestResponse
Resource = "directions/json?origin=" & Origin & "&destination=" & Destination & "&sensor=false"
Set Response = MapsClient.GetJSON(Resource)
' => GET https://maps.../api/directions/json?origin=...&destination=...&sensor=false
ProcessDirections Response
End Function
Public Sub ProcessDirections(Response As RestResponse)
If Response.StatusCode = Ok Then
Dim Route As Dictionary
Set Route = Response.Data("routes")(1)("legs")(1)
Debug.Print "It will take " & Route("duration")("text") & _
" to travel " & Route("distance")("text") & _
" from " & Route("start_address") & _
" to " & Route("end_address")
Else
Debug.Print "Error: " & Response.Content
End If
End SubThere are 3 primary components in Excel-REST:
RestRequestfor defining complex requestsRestClientfor executing requestsRestResponsefor dealing with responses.
In the above example, the request is fairly simple, so we can skip creating a RestRequest and instead use the Client.GetJSON helper to GET json from a specific url. In processing the response, we can look at the StatusCode to make sure the request succeeded and then use the parsed json in the Data parameter to extract complex information from the response.
If we wish to have more control over the request, the following example uses RestRequest to define a complex request.
Function GetDirections(Origin As String, Destination As String) As String
Dim MapsClient As New RestClient
' ... Setup client using GetJSON Example
' Create a RestRequest for getting directions
Dim DirectionsRequest As New RestRequest
DirectionsRequest.Resource = "directions/{format}"
DirectionsRequest.Method = httpGET
' Set the request format -> Sets {format} segment, content-types, and parses the response
DirectionsRequest.Format = json
' (Alternatively, replace {format} segment directly)
DirectionsRequest.AddUrlSegment "format", "json"
' Add parameters to the request (as querystring for GET calls and body otherwise)
DirectionsRequest.AddParameter "origin", Origin
DirectionsRequest.AddParameter "destination", Destination
' Force parameter as querystring for all requests
DirectionsRequest.AddQuerystringParam "sensor", "false"
' => GET https://maps.../api/directions/json?origin=...&destination=...&sensor=false
' Execute the request and work with the response
Dim Response As RestResponse
Set Response = MapsClient.Execute(DirectionsRequest)
ProcessDirections Response
End Function
Public Sub ProcessDirections(Response As RestResponse)
' ... Same as previous examples
End SubThe above example demonstrates some of the powerful feature available with RestRequest. Some of the features include:
- Url segments (Replace {segment} in resource with value)
- Method (GET, POST, PUT, PATCH, DELETE)
- Format (json and url-encoded) for content-type and converting/parsing request and response
- Parameters and QuerystringParams
- Body
- Cookies
- Headers
For more details, see the RestRequest page in with Wiki
The following example demonstrates using an authenticator with Excel-REST to query Twitter. The TwitterAuthenticator (found in the authenticators/ folder) uses Twitter's OAuth 1.0a authentication and details of how it was created can be found in the Wiki.
Function QueryTwitter(query As String) As RestResponse
Dim TwitterClient As New RestClient
TwitterClient.BaseUrl = "https://api.twitter.com/1.1/"
' Setup authenticator
Dim TwitterAuth As New TwitterAuthenticator
TwitterAuth.Setup _
ConsumerKey:="Your consumer key", _
ConsumerSecret:="Your consumer secret"
Set TwitterClient.Authenticator = TwitterAUth
' Setup query request
Dim Request As New RestRequest
Request.Resource = "search/tweets.{format}"
Request.Format = json
Request.Method = httpGET
Request.AddParameter "q", query
Request.AddParameter "lang", "en"
Request.AddParameter "count", 20
' => GET https://api.twitter.com/1.1/search/tweets.json?q=...&lang=en&count=20
' Authorization Bearer Token... (received and added automatically via TwitterAuthenticator)
Set QueryTwitter = TwitterClient.Execute(Request)
End FunctionFor more details, check out the Wiki and Examples
- Mac support!
- Custom converters
- Switch to
WinHttpRequest - Switch to VBA-tools/VBA-JSON
- Add
Request.RequestFormat,Request.ResponseFormat, andRequest.Acceptfor setting separate request and response formats (e.g. form-urlencoded request with json response) - Add
LogRequestandLogResponsefor better logging detail (enable withRestHelpers.EnableLogging = True) - Allow headers and content-type to be set in authenticator
BeforeExecute - 3.1.1 Fix importing class incorrectly as module bug
- 3.1.2 Add XML and plain text formats
- 3.1.3 Fix hard dependency for XML
- 3.1.4 Fix logging in
PrepareProxyForHttpRequest
- Add
Client.GetJSONandClient.PostJSONhelpers to GET and POST JSON without setting up request - Add
AfterExecutetoIAuthenticator(Breaking change, all IAuthenticators must implement this new method) - 3.0.1 Add
DigestAuthenticator, new helpers, and cleanup - 3.0.2 Switch timeout to
Longand removeRestClientBase(out of sync with v3) - 3.0.3 Update OAuth1, deprecate
IncludeCacheBreaker, update True/False formatting to lowercase, add LinkedIn example - 3.0.4 Fix formatting of parameters with spaces for OAuth1 and add logging
- 3.0.5 Allow Array and Collection for Body in
Request.AddBodyandClient.PostJSON - 3.0.6 Convert Empty to
nullfor json - 3.0.7 Add
install.batscript for easy installation and upgrade
- Add
form-urlencodedformat and helpers - Combine Body + Parameters and Querystring + Parameters with priority given to Body or Querystring, respectively
- Add cookies support with
Request.AddCookie(key, value)andResponse.Cookies - 2.2.1 Add
Response.Headerscollection of response headers
- Add Microsoft Scripting Runtime dependency (for Dictionary support)
- Add
RestClient.SetProxyfor use in proxy environments - 2.1.1 Use
Valfor number parsing in locale-dependent settings - 2.1.2 Add raw binary
BodytoRestResponsefor handling files (thanks @berkus) - 2.1.3 Bugfixes and refactor
- Remove JSONLib dependency (merged with RestHelpers)
- Add RestClientBase for future use with extension for single-client applications
- Add build scripts for import/export
- New specs and bugfixes
- 2.0.1 Handle duplicate keys when parsing json
- 2.0.2 Add Content-Length header and 408 status code for timeout
Major Changes:
- Integrate Excel-TDD to fully test Excel-REST library
- Handle timeouts for sync and async requests
- Remove reference dependencies and use CreateObject instead
Bugfixes:
- Add cachebreaker as querystring param only
- Add Join helpers to resolve double-slash issue between base and resource url
- Only add "?" for querystring if querystring will be created and "?" isn't present
- Only put parameters in body if there are parameters
- Add async support
- Design based heavily on the awesome RestSharp
- Author: Tim Hall
- License: MIT