On the internet, you can find a plethora of articles on handling HTTP requests in Power Query. Most descriptions focus on accessing Public APIs: Websites and various public Web Services. However, REST API interfaces are equally standard for various on-premises Enterprise Applications. Despite the common approaches and use of the same basic PQ functions, there are specific considerations when working with business applications such as ERP, CPM, CRM, etc. While working on the Planning Analytics Model Explorer, I encountered some of these nuances, leading me to develop an extended function for forming HTTP requests to such systems. Below, I will delve into its peculiarities and provide a link to the source code at the end of the post.
Possible limitations on the number of simultaneous connections
The basic PQ function for managing HTTP requests, Web.Contents, automatically retries requests that fail with certain status codes. By default, the function makes up to three attempts to receive a response from the web service. An exponential back-off algorithm determines how long to wait until the next retry. At the same time, the client may send several different requests to the server simultaneously, and if the server is overloaded or temporarily unavailable, it may make sense to suspend the sending of new requests.
Simultaneously, web services of any type, whether public or internal, often have RPS/RPM (Requests Per Second/ Requests Per Minute) limitations on the number of HTTP requests that can be sent to them from a single client. These limitations are implemented for several reasons, such as ensuring that the service can maintain high performance and availability for all users and protection against abusive behaviors such as denial-of-service attacks.
In Enterprise Applications, there may be an additional limitation on connections from a single client related to licensing policies on concurrent connections. For example, in IBM Planning Analytics, a legacy parameter MaximumPorts, still exists, limiting the number of simultaneous client sessions.
Therefore, if the client application sends multiple requests to the server simultaneously, and we know in advance the limitation on the number of sessions allocated to the client, we can apply the so-called “API throttling” technique. It involves deliberately pacing the client’s requests to stay within the rate limits of the web service we are interacting with. Instead of sending requests as fast as possible, we may send a ” batch” of requests, wait for some time, and then send another batch.
Implementation of a Simple API Throttling Strategy
Microsoft suggests a custom Wait-Retry Pattern to modify the default behavior of the Web.Contents function. The solution is concise and elegant, but without additional modifications, it is unsuitable for implementing parallel requests batching. To implement such a technique, we will need:
- To add a request sequence number. While we can only control the “parallelism” of requests in Power Query to a limited extent, assigning an incremental number to each request allows us to distribute them into “deferred buckets.”
- Modify the “interval” function while preserving the exponential back-off algorithm for retrying a request with the same number. In my case, this is the calculated value of RequestDelay.
In addition, the original function ideally should include error handling mechanisms and server response logging.
The original Wait-Retry Pattern from Microsoft implements building a list of retry attempts using the List.Generate function. While elegant, complex usage cases of this function can often be challenging to debug. Therefore, for request retries, I implemented a straightforward recursive call.
Errors Handling and Logging
In addition to catching standard HTTP request error codes, the function implements handling and logging of the following types of errors:
- The remote server is unavailable.
- Incorrect connection parameters (host, port) or authentication credentials are provided.
- An incorrect authentication method is used.
- An HTTP request is sent when an encrypted HTTPS request is expected, and vice versa.
- The application server uses a self-signed certificate.
- The server received an incorrect HTTP request.
The result of executing (or failing to execute) a request is placed in the SysHttpRequestLog table. The number of execution attempts for each request type, a description and the reason for the error (if the request was not executed), as well as other service information, are logged.
Example of logging:

PQ Code
The complete Power BI project, including the function, http requests samples, and logging tables, is available on GitHub. For clarity and quick access, the main PQ code for the final function is provided below:
let func = (RequestContent as text, optional RawBody as text, optional RequstNo as nullable number) =>
let
//fn_checkRequestError Start
fn_checkRequestError = (Response as nullable any, ServerResponse as nullable any) as record =>
if Response[HasError]?
then [HasError = Response[HasError]?, ErrorReason = Response[Error]?[Reason]?, ErrorMessage = Response[Error]?[Message]?, ErrorDetails = Response[Error]?[Details]?]
else
if ServerResponse[HasError]?
then [ HasError = ServerResponse[HasError]?, ErrorReason = ServerResponse[Error]?[Reason]?, ErrorMessage = ServerResponse[Error]?[Message]?, ErrorDetails = ServerResponse[Error]?[Details]? ]
else if not ServerResponse[HasError] and ServerResponse[Value] = null
then [ HasError = true, ErrorReason = "Unknown", ErrorMessage = "Incorrect connection or authorization parameters may have been specified", ErrorDetails = null ]
else [ HasError = false, ErrorReason = null, ErrorMessage = null, ErrorDetails = null ],
//fn_checkRequestError End
//fn_trySendReques Start
fn_trySendRequest = (AttemptNo as number, ResponseMetaData as table) =>
let
// Request parameteres
NumberInPool = if (RequstNo = null) then 1 else RequstNo,
RequestDelay = (Number.IntegerDivide(NumberInPool - 1, HttpRequestPool) + 1) * HttpRequestLatencySec * Number.Power(2, (AttemptNo - 1)) - HttpRequestLatencySec, // throttling
// Request URL, headers, options
// Avoiding a dynamic data source when updating on the Service
Request = #"HTTP(S)://HOST:PORT" & PATH,
Options = [
Headers = [
#"Authorization" = AuthType & " " & Auth,
#"Content-Type" = "application/json;charset=utf-8",
#"Cache-Control" = "no-cache, must-revalidate"
],
RelativePath = RequestContent,
Content = Text.ToBinary(RawBody),
Timeout = #duration(0, 0, 0, HttpRequestTimeoutSec),
IsRetry = true,
ManualStatusHandling =
{
200, 201, 202, // Success, record the request result
408, 429, 503, 504, 509, // Handled error, repeat the request, if failure again - record the request result
401, 403, 404 // Handled error, record the request result
}
],
//Send Request & BufferData
SendRequest = Function.InvokeAfter( () => try Web.Contents(Request, Options), #duration(0, 0, 0, RequestDelay) ),
BufferedData = SendRequest[[HasError]] & [Value = Binary.Buffer(SendRequest[Value])], //avoid a risk of multple PQ calls
ResponseStatus = try Value.Metadata(SendRequest[Value]?)[Response.Status]?,
Error = fn_checkRequestError(BufferedData, ResponseStatus),
HttpResponseStatus = if ResponseStatus[HasError]? then null else ResponseStatus[Value],
RequestResponseTime = if HttpResponseStatus <> null then DateTime.LocalNow() else null, // avoid lazy evaluation
AppendResponseMetaData = Table.InsertRows( ResponseMetaData
, Table.RowCount(ResponseMetaData)
, {[ RequstNo = RequstNo
, RequestContent = RequestContent
, RequestBody = RawBody
, AttemptNo = AttemptNo
, RequestDelay = RequestDelay
, RequestResponseTime = RequestResponseTime
, HasConnectionError = Error[HasError]
, ConnectionErrorReason = Error[ErrorReason]
, ConnectionErrorMessage = Error[ErrorMessage]
, ConnectionErrorDetails = Error[ErrorDetails]
, HttpResponseStatus = HttpResponseStatus
]}
),
RequestResult = if (Error[HasError])
then
Record.AddField([], "@metadata", AppendResponseMetaData)
else
let
HttpRequestResult = if (List.MatchesAny({408, 429, 503, 504, 509}, each _ = HttpResponseStatus) and AttemptNo < HttpRequestMaxAttempts)
then
@fn_trySendRequest(AttemptNo + 1, AppendResponseMetaData) // Repeat the request
else
Record.AddField(try Json.Document(BufferedData[Value]) otherwise [], "@metadata", AppendResponseMetaData) // Add @metadata field to the request result
in
HttpRequestResult
in
RequestResult,
//fn_trySendReques End
AuthType = "Basic",
Auth = Binary.ToText(
Text.ToBinary(LOGIN & ":" & PASSWORD
)
, BinaryEncoding.Base64),
HttpRequestPool = SettingsConfigDefault[HttpRequestPool],
HttpRequestLatencySec = SettingsConfigDefault[HttpRequestLatencySec],
HttpRequestMaxAttempts = SettingsConfigDefault[HttpRequestMaxAttempts],
HttpRequestTimeoutSec = SettingsConfigDefault[HttpRequestTimeoutSec],
ResponseTable = fn_trySendRequest(1, #table(type table[
RequstNo = number
, RequestContent = text
, RequestBody = text
, AttemptNo = number
, RequestDelay = number
, RequestResponseTime = datetime
, HasConnectionError = logical
, ConnectionErrorReason = text
, ConnectionErrorMessage = text
, ConnectionErrorDetails = text
, HttpResponseStatus = number
], {}) )
in
ResponseTable,
documentation = [
Documentation.Name = " fn_sendHttpRequest",
Documentation.Description = " ",
Documentation.LongDescription = " Managing HTTP requests",
Documentation.Category = " Data extraction ",
Documentation.Source = " ",
Documentation.Version = " 1.82.bc ",
Documentation.Author = " Alex Zaitsev ",
Documentation.Examples = {[Description = "",
Code = " fn_sendHttpRequest( ""Users"", null, 1 ) ",
Result = "A record in the format [ @odata.context as text, value as List, @metadata as Table ]"]}
]
in
Value.ReplaceType(func, Value.ReplaceMetadata(Value.Type(func), documentation))
priligy 30mg tablets
priligy 30mg tablets
semaglutida elea inyectable para que sirve
semaglutida elea inyectable para que sirve
was ist besser semaglutid oder tirzepatid
was ist besser semaglutid oder tirzepatid
semaglutid tabletten novo nordisk
semaglutid tabletten novo nordisk
doxycycline side effects fertility
doxycycline side effects fertility
acyclovir ingredients
acyclovir ingredients
bupropion dosage recommendations
bupropion dosage recommendations
ketoconazole indication reference
ketoconazole indication reference
ketorolac tromethamine medical info
ketorolac tromethamine medical info
toradol short term safety
toradol short term safety
ivermectin scabies symptom improvement
ivermectin scabies symptom improvement
ivermectin PK mechanism link
ivermectin PK mechanism link
minoxidil 2% vs 5% full review
minoxidil 2% vs 5% full review
minoxidil foam vs liquid full comparison
minoxidil foam vs liquid full comparison
minoxidil women’s 12‑month results
minoxidil women’s 12‑month results
avanafil effect classification
avanafil effect classification
sinusitis infection overview
sinusitis infection overview
Alcohol and Sildenafil Onset
Alcohol and Sildenafil Onset
TadalafilCentral online tadalafil guide
TadalafilCentral online tadalafil guide