Introduction
Installation
- Download the latest release (v4.1.6)
- To install/upgrade in an existing file, use
VBA-Web - Installer.xlsm
- To start from scratch in Excel,
VBA-Web - Blank.xlsm
has everything setup and ready to go
WebRequest
WebRequest
is used to create detailed requests (including formatting, querystrings, headers, cookies, and much more).
Usage:
Properties
Resource
Get|Let {String}
Set the request’s portion of the url to be appended to the client’s BaseUrl
.
Can include Url Segments for dynamic values
and Querystring parameters
are smart enough to be appended to existing querystring
(or added to resource if there isn’t an existing querystring).
Method
Get|Let {WebMethod}
Set the HTTP method to be used for the request: GET, POST, PUT, PATCH, DELETE
Body
Get|Let|Set {Variant}
Get
Body value converted to string using
RequestFormat
orCustomRequestFormat
Let
Use
String
orArray
for BodySet
Use
Collection
,Dictionary
, orObject
for Body
Format
Get|Let {WebFormat}
Set RequestFormat
, ResponseFormat
, and Content-Type
and Accept
headers for the WebRequest
RequestFormat
Get|Let {WebFormat}
Set the format to use for converting the response Body
to string and for the Content-Type
header
Note If WebFormat.Custom
is used, the CustomRequestFormat
must be set.
ResponseFormat
Get|Let {WebFormat}
Set the format to use for converting the response Content
to Data
and for the Accept
header
Note If WebFormat.Custom
is used, the CustomResponseFormat
must be set.
CustomRequestFormat
Get|Let {String}
Use converter registered with WebHelpers.RegisterConverter
to convert Body
to string and set Content-Type
header.
(Automatically sets RequestFormat
to WebFormat.Custom
)
CustomResponseFormat
Get|Let {String}
Use converter registered with WebHelpers.RegisterConverter
to convert the response Content
to Data
and set Accept
header.
(Automatically sets ResponseFormat
to WebFormat.Custom
)
ContentType
Get|Let {String}
Set automatically from RequestFormat
or CustomRequestFormat
,
but can be overriden to set Content-Type
header for request.
Accept
Get|Let {String}
Set automatically from ResponseFormat
or CustomResponseFormat
,
but can be overriden to set Accept
header for request.
ContentLength
Get|Let {Long}
Set automatically by length of Body
,
but can be overriden to set Content-Length
header for request.
FormattedResource
Get {String}
Get Resource
with Url Segments replaced and Querystring added.
Cookies
Get|Set Collection
Note To add cookies, use AddCookie
.
Collection
of Cookies to include with request,
stored as KeyValue
(Dictionary: {Key: "...", Value: "..."}
).
Headers
Get|Set Collection
Note To add headers, use AddHeader
.
Collection
of Headers to include with request,
stored as KeyValue
(Dictionary: {Key: "...", Value: "..."}
).
QuerystringParams
Get|Set Collection
Note To add Querystring parameters, use AddQuerystringParam
.
Collection
of Querystring parameters to include with request,
stored as KeyValue
(Dictionary: {Key: "...", Value: "..."}
).
UrlSegments
Get|Set Dictionary
Note To add Url Segments, use AddUrlSegment
Url Segments are used to easily add dynamic values to Resource
.
Create a Url Segement in Resource
with curly brackets and then
replace with dynamic value with AddUrlSegment
.
Methods
AddHeader
AddHeader(Key, Value)
Key
{String}
Value
{Variant}
Add header to be sent with request
SetHeader
SetHeader(Key, Value)
Key
{String}
Value
{Variant}
Add/replace header to be sent with request.
SetHeader
should be used for headers that can only be included once with a request
(e.g. Authorization, Content-Type, etc.).
AddUrlSegment
AddUrlSegment(Key, Value)
Key
{String}
Value
{Variant}
Url Segments are used to easily add dynamic values to Resource
.
Create a Url Segement in Resource
with curly brackets and then
replace with dynamic value with AddUrlSegment
.
AddQuerystringParam
AddQuerystringParam(Key, Value)
Key
{String}
Value
{Variant}
Add querysting parameter to be used in FormattedResource
for request.
AddCookie
AddCookie(Key, Value)
Key
{String}
Value
{Variant}
Add cookie to be sent with request.
AddBodyParameter
AddBodyParameter(Key, Value)
Key
{Variant}
Value
{Variant}
Add Key-Value
to Body
. Body
must be a Dictionary
(if it’s an Array
or Collection
an error is thrown).
CreateFromOptions
CreateFromOptions(Options)
Options
{Dictionary}
Options("Headers")
{Collection}
Optional Collection ofKeyValue
Options("Cookies")
{Collection}
Optional Collection ofKeyValue
Options("QuerystringParams")
{Collection}
Optional Collection ofKeyValue
Options("UrlSegments")
{Dictionary}
Optional
WebClient
WebClient
executes requests and handles response and is responsible for functionality shared between requests,
such as authentication, proxy configuration, and security.
Usage:
Properties
BaseUrl
Get|Let {String}
Set the base url that is shared by all requests
and that the request Resource
is appended to.
Authenticator
Get|Set {IWebAuthenticator}
Attach an authenticator to the client for authentication requests.
TimeoutMs
Get|Let {Long}
Timeout (in milliseconds) to wait for timeout in each request phase (Resolve, Connect, Send, Receive).
ProxyServer
Get|Let {String}
Proxy server to pass requests through (except for those that match ProxyBypassList
).
ProxyBypassList
Get|Let {String}
Comma separated list of domains to bypass the proxy.
ProxyUsername
Get|Let {String}
Username for proxy.
ProxyPassword
Get|Let {String}
Password for proxy.
EnableAutoProxy
Get|Let {Boolean}
Load proxy server and bypass list automatically (False
by default).
Insecure
Get|Let {Boolean}
Turn off SSL validation (False
by default).
Useful for self-signed certificates and should only be used with trusted servers.
FollowRedirects
Get|Let {Boolean}
Follow redirects (301, 302, 307) using Location header (True
by default).
Methods
Execute
Execute(Request) {WebResponse}
Request
{WebRequest}
Execute the given request
(append the request’s FormattedResource
to the BaseUrl
)
and return the response.
GetJson
GetJson(Url, [Options]) {WebResponse}
Url
{String}
Options
{Dictionary}
Optional Headers, Cookies, QuerystringParams, and UrlSegmentsHeaders
,Cookies
,QuerystringParams
:Collection
ofKeyValue
(Create withWebHelpers.CreateKeyValue
)UrlSegments
:Dictionary
Get JSON from the given URL (with options for Headers, Cookies, QuerystringParams, and UrlSegments).
PostJson
PostJson(Url, Body, [Options]) {WebResponse}
Url
{String}
Body
{Variant}
Array
,Collection
, orDictionary
to postOptions
{Dictionary}
Optional Headers, Cookies, QuerystringParams, and UrlSegmentsHeaders
,Cookies
,QuerystringParams
:Collection
ofKeyValue
(Create withWebHelpers.CreateKeyValue
)UrlSegments
:Dictionary
Post JSON Body (Array
, Collection
, Dictionary
) to the given URL
(with options for Headers, Cookies, QuerystringParams, and UrlSegments).
SetProxy
SetProxy(Server, [Username], [Password], [BypassList])
Server
{String}
Proxy server to pass requests throughUsername
{String}
Optional Username for proxyPassword
{String}
Optional Password for proxyBypassList
{String}
Optional Comma-separated list of servers that should bypass proxy
Helper for setting proxy values.
GetFullUrl
GetFullUrl(Request) {String}
Request
{WebRequest}
Get full url by joining given WebRequest.FormattedResource
and BaseUrl
.
WebResponse
Wrapper for http/cURL responses that includes parsed Data
based on WebRequest.ResponseFormat
.
Usage:
Properties
StatusCode
Get|Let {WebStatusCode}
Status code that the server returned (e.g. 200).
StatusDescription
Get|Let {String}
Status string that the server returned
(e.g. 404 -> "Not Found"
).
Content
Get|Let {String}
Content string that the server returned.
Data
Get|Set {Object}
Parsed Content
or Body
based on the WebRequest.ResponseFormat
.
Body
Get|Let {Variant}
Raw bytes for the response.
Headers
Get|Set {Collection}
Headers that were included with the response (Collection
of KeyValue
).
Cookies
Get|Set {Collection}
Cookies that were included with the response (Collection
of KeyValue
).
Methods
Update
Update(Updated)
Updated
{WebResponse}
Helper for updating the response with the given updated response values.
Useful for ByRef
cases to update response in place.
WebHelpers
Contains general-purpose helpers that are used throughout VBA-Web. Includes:
- Logging
- Converters and encoding
- Url handling
- Object/Dictionary/Collection/Array helpers
- Request preparation / handling
- Timing
- Mac
- Cryptography
- Converters (JSON, XML, Url-Encoded)
Properties
WebStatusCode
{WebStatusCode}
Ok
200
Created
201
NoContent
204
BadRequest
400
Unauthorized
401
Forbidden
403
NotFound
404
RequestTimeout
408
UnsupportedMediaType
415
InternalServerError
500
BadGateway
502
ServiceUnavailable
503
GatewayTimeout
504
Helper for common http status codes. (Use underlying status code for any codes not listed)
WebMethod
{WebMethod}
HttpGet
0
HttpPost
1
HttpPut
2
HttpDelete
3
HttpPatch
4
WebFormat
{WebFormat}
PlainText
0
Json
1
FormUrlEncoded
2
Xml
3
Custom
4
UrlEncodingMode
{UrlEncodingMode}
StrictUrlEncoding
0
FormUrlEncoding
1
QueryUrlEncoding
2
CookieUrlEncoding
3
PathUrlEncoding
4
StrictUrlEncoding
uses RFC 3986 and is the defaultFormUrlEncoding
uses HTML5 form url-encoding and is used withWebFormat.FormUrlEncoded
QueryUrlEncoding
uses subset ofStrict
andForm
for default querystring encodingCookieUrlEncoding
uses RFC 6265PathUrlEncoding
uses “pchar” from RFC 3986 and is the default
EnableLogging
Get|Let {Boolean}
Enable logging of requests and responses and other internal messages from VBA-Web.
Should be the first step in debugging VBA-Web if something isn’t working as expected.
(Logs display in Immediate Window (View > Immediate Window
or ctrl+g
)
Methods
LogDebug
LogDebug(Message, [From])
Message
{String}
From
{String}
Optional
Log message (when logging is enabled with EnableLogging
)
with optional location where the message is coming from.
Useful when writing extensions to VBA-Web (like an IWebAuthenticator
).
LogWarning
LogWarning(Message, [From])
Message
{String}
From
{String}
Optional
Log warning (even when logging is disabled with EnableLogging
)
with optional location where the message is coming from.
Useful when writing extensions to VBA-Web (like an IWebAuthenticator
).
LogError
LogError(Message, [From], [ErrNumber])
Message
{String}
From
{String}
OptionalErrNumber
{Long}
Optional
Log error (even when logging is disabled with EnableLogging
)
with optional location where the message is coming from and error number.
Useful when writing extensions to VBA-Web
(like an IWebAuthenticator
).
LogRequest
LogRequest(Client, Request)
Client
{WebClient}
Request
{WebRequest}
Log details of the request (Url, headers, cookies, body, etc.).
LogResponse
LogResponse(Client, Request, Response)
Client
{WebClient}
Request
{WebRequest}
Response
{WebResponse}
Log details of the response (Status, headers, content, etc.).
Obfuscate
Obfuscate(Secure, [Character])
Secure
{String}
Message to obfuscateCharacter
{String}
Optional Character to obfuscate with (“*” is default)
Obfuscate any secure information before logging.
ParseJson
ParseJson(Value) {Object}
Value
{String}
JSON value to parse
Parse JSON value to Dictionary
if it’s an object or Collection
if it’s an array.
ConvertToJson
ConvertToJson(Value, [Whitespace]) {String}
Value
{Variant}
Dictionary
,Collection
, orArray
to convert to stringWhitespace
{Integer|String}
Pretty-print with given number of spaces or string per indentation
Convert Dictionary
, Collection
, or Array
to JSON string.
ParseUrlEncoded
ParseUrlEncoded(Value) {Dictionary}
Value
{String}
Url-Encoded value to parse
Parse Url-Encoded value to Dictionary
.
ConvertToUrlEncoded
ConvertToUrlEncoded(Obj, [EncodingMode = FormUrlEncoding]) {String}
Obj
{Dictionary|Collection|Variant}
Value to convert to Url-Encoded stringEncodingMode
{UrlEncodingMode}
Optional Default isUrlEncodingMode.FormUrlEncoding
Convert Dictionary
/Collection
to Url-Encoded string.
ParseXml
ParseXml(Value) {Dictionary}
Value
{String}
Encoded XML value to parse
Parse XML value to Dictionary
.
Note Currently, XML is not supported in 4.0.0 due to lack of Mac support.
An updated parser is being created that supports Mac and Windows,
but in order to avoid future breaking changes, ParseXml
and ConvertToXml
are not currently implemented.
See XML Support in 4.0 for details on how to use XML in Windows in the meantime.
ConvertToXml
ConvertToXml(Value) {String}
Value
Dictionary|Variant
XML
Convert Dictionary
to XML string.
Note Currently, XML is not supported in 4.0.0 due to lack of Mac support.
An updated parser is being created that supports Mac and Windows,
but in order to avoid future breaking changes, ParseXml
and ConvertToXml
are not currently implemented.
See XML Support in 4.0 for details on how to use XML in Windows in the meantime.
ParseByFormat
ParseByFormat(Value, Format, [CustomFormat], [Bytes]) {Object}
Value
{String}
Value to parseFormat
{WebFormat}
CustomFormat
{String}
Optional Name of registered custom converterBytes
{Variant}
Optional Bytes for custom converter (ifParseType = "Binary"
)
Helper for parsing value to given WebFormat
or custom format.
Returns Dictionary
or Collection
based on given Value
.
ConvertToFormat
ConvertToFormat(Value, Format, [CustomFormat]) {String}
Value
{Dictionary|Collection|Variant}
Dictionary
,Collection
, orArray
to convert to stringFormat
{WebFormat}
CustomFormat
{String}
Optional Name of registered custom converter
Helper for converting value to given WebFormat
or custom format.
Note Only some converters handle Collection
or Array
.
UrlEncode
UrlEncode(Text, [SpaceAsPlus = False], [EncodeUnsafe = True], [EncodingMode = StrictUrlEncoding]) {String}
Text
{Variant}
Text to encodeSpaceAsPlus
{Boolean}
Optional Default isFalse
DEPRECATED Use
EncodingMode:=FormUrlEncoding
EncodeUnsafe
{Boolean}
Optional Default isTrue
DEPRECATED This was based on an outdated URI spec and has since been removed.
EncodingMode:=CookieUrlEncoding
is the closest approximation of this behaviorEncodingMode
”
{UrlEncodingMode}
Optional Default isUrlEncodingMode.StrictUrlEncoding
”
Encode string for URLs (Reference).
UrlDecode
UrlDecode(Encoded, [PlusAsSpace = True], [EncodingMode = StrictUrlEncoding]) {String}
Encoded
{String}
Text to decodePlusAsSpace
{Boolean}
Optional Default isTrue
DEPRECATED Use
EncodingMode:=FormUrlEncoded
orQueryUrlEncoding
EncodingMode
”
{UrlEncodingMode}
Optional Default isUrlEncodingMode.StrictUrlEncoding
”
Decode Url-encoded string.
Base64Encode
Base64Encode(Text) {String}
Text
{String}
Text to encode
Base64-encode text.
Base64Decode
Base64Decode(Encoded) {String}
Encoded
{String}
Text to decode
Decode Base64-encoded text
RegisterConverter
RegisterConverter(Name, MediaType, ConvertCallback, ParseCallback, [Instance], [ParseType])
Name
{String}
Name of converter for use withCustomRequestFormat
orCustomResponseFormat
MediaType
{String}
Media type to use forContent-Type
andAccept
headersConvertCallback
{String}
Global or object function name for convertingParseCallback
{String}
Global or object function name for parsingInstance
{Object}
Optional Use instance methods forConvertCallback
andParseCallback
ParseType
{String}
Optional"String"
(default) or"Binary"
to pass raw binary response toParseCallback
Register custom converter for converting request Body
and response Content
.
If the ConvertCallback
or ParseCallback
are object methods,
pass in an object instance.
If the ParseCallback
needs the raw binary response value (e.g. file download),
set ParseType = "Binary"
, otherwise "String"
is used.
ConvertCallback
signature:Function ...(Value As Variant) As String
ParseCallback
signature:Function ...(Value As String) As Object
JoinUrl
JoinUrl(LeftSide, RightSide) {String}
LeftSide
{String}
RightSide
{String}
Join two url parts, handling “/” in between them.
UrlParts
UrlParts(Url) {Dictionary}
Url
{String}
Get relevant parts of the given url. Returns Protocol
, Host
, Port
, Path
, Querystring
, and Hash
.
CloneDictionary
CloneDictionary(Dict) {Dictionary}
Dict
{Dictionary}
Create a cloned copy of the Dictionary
.
This is not a deep copy, so children objects are copied by reference.
CloneCollection
CloneCollection(Coll) {Collection}
Coll
{Collection}
Create a cloned copy of the Collection
.
This is not a deep copy, so children objects are copied by reference.
CreateKeyValue
CreateKeyValue(Key, Value) {Dictionary}
Key
{String}
Value
{Variant}
Helper for creating Key-Value
pair with Dictionary
.
Used in WebRequest
/WebResponse
Cookies
, Headers
, and QuerystringParams
FindInKeyValues
FindInKeyValues(KeyValues, Key) {Variant}
KeyValues
{Collection}
ofKey-Value
Key
{Variant}
Search a Collection
of Key-Value
and retrieve the value for the given key.
AddOrReplaceInKeyValues
AddOrReplaceInKeyValues(KeyValues, Key, Value)
KeyValues
{Collection}
Key
{String}
Value
{Variant}
Helper for adding/replacing KeyValue
in Collection
of KeyValue
- Add if key not found
- Replace if key is found
FormatToMediaType
FormatToMediaType(Format, [CustomFormat]) {String}
Format
{WebFormat}
CustomFormat
{String}
Optional Needed ifFormat = WebFormat.Custom
Get the media-type for the given format / custom format.
MethodToName
MethodToName(Method) {String}
Method
{WebMethod}
Get the method name for the given WebMethod
HMACSHA1
HMACSHA1(Text, Secret, [Format]) {String}
Text
{String}
Secret
{String}
Format
{String}
Optional"Hex"
or"Base64"
encoding for result
Determine the HMAC for the given text and secret using the SHA1 hash algorithm.
HMACSHA256
HMACSHA256(Text, Secret, [Format]) {String}
Text
{String}
Secret
{String}
Format
{String}
Optional"Hex"
or"Base64"
encoding for result
Determine the HMAC for the given text and secret using the SHA256 hash algorithm.
MD5
MD5(Text, [Format]) {String}
Text
{String}
Format
{String}
Optional"Hex"
or"Base64"
encoding for result
Determine the MD5 hash of the given text.
CreateNonce
CreateNonce([NonceLength])
NonceLength
{Integer}
Optional Default is 32
Create random alphanumeric nonce (0-9a-zA-Z)
IWebAuthenticator
Interface for creating authenticators for WebClients.
EmptyAuthenticator
has everything setup for creating your own authenticators.
See Implementing your own IWebAuthenticator for a detailed guide on creating an authenticator.
Methods
BeforeExecute
BeforeExecute(Client, Request)
Client
{WebClient}
Request
ByRef {WebRequest}
The request about to be executed
Hook for taking action before a request is executed. Useful for adding headers (e.g. “Authorization”), cookies, etc.
AfterExecute
AfterExecute(Client, Request, Response)
Client
{WebClient}
Request
{WebRequest}
The request that was just executedResponse
ByRef {WebResponse}
Hook for taking action after a request has been executed.
Useful for handling 401 Unauthorized
or other issues.
PrepareHttp
PrepareHttp(Client, Request, Http)
Client
{WebClient}
Request
{WebRequest}
Http
{WinHttpRequest}
Hook for updating http before send. Useful for setting internal http options (WinHttpRequest Docs).
PrepareCurl
PrepareCurl(Client, Request, Curl)
Client
{WebClient}
Request
{WebRequest}
Curl
{String}
Hook for update cURL command before send. Useful for setting internal cURL options (cURL Docs)
WebAsyncWrapper
Wrapper WebClient and WebRequest that enables callback-style async requests
Note Windows-only and Excel-only and requires reference to "Microsoft WinHTTP Services, version 5.1"
Usage:
Properties
Client
Get|Set {WebClient}
Client to use for executing requests.
Methods
ExecuteAsync
ExecuteAsync(Request, Callback, [CallbackArgs])
Request
{WebRequest}
Callback
{String}
CallbackArgs
{Variant}
Optional
Execute the given WebRequest
asynchronously,
passing the response (and CallbackArgs
if given) to the Callback
.