Uri.BuildQueryString

D

T

The M Code Behind the Power Query M function Uri.BuildQueryString

The `Uri.BuildQueryString` function takes a record as input, and returns a string that represents the query string. The input record can contain any number of fields, and each field represents a parameter that is included in the query string. Here is an example of how the `Uri.BuildQueryString` function can be used:


let

params = [

param1 = "value1",

param2 = "value2",

param3 = "value3"

],

queryString = Uri.BuildQueryString(params)

in

queryString


In this example, a record is created that contains three fields, and the `Uri.BuildQueryString` function is called with this record as input. The resulting string represents the query string `param1=value1&param2=value2&param3=value3`.

Understanding the M Code

To understand how the `Uri.BuildQueryString` function works, it is necessary to look at the M code that powers it. Here is the M code for the `Uri.BuildQueryString` function:


let

BuildQueryString = (params as record) =>

let

paramList = Record.ToList(params),

queryString = Text.Combine(List.Transform(paramList, each Text.Combine({Uri.EscapeDataString(Text.From(_{0})), "=", Uri.EscapeDataString(Text.From(_{1}))}, "=")), "&")

in

queryString

in

BuildQueryString


The `Uri.BuildQueryString` function is defined as a `let` expression, which allows for the creation of variables that can be used in subsequent expressions. The input to the function is a record, which is stored in the `params` variable.

The `Record.ToList` function is used to convert the record to a list of key-value pairs. Each key-value pair is represented as a two-element list, where the first element is the key and the second element is the value.

The `List.Transform` function is used to transform each key-value pair in the list into a string that represents a single parameter in the query string. This is done using the `Text.Combine` function, which concatenates the key and value with an equals sign.

The `Uri.EscapeDataString` function is used to escape any characters in the key or value that are not allowed in a URL. This ensures that the resulting query string is valid and can be used in a URL.

Finally, the `Text.Combine` function is used again to concatenate all of the parameters into a single string, with each parameter separated by an ampersand.

The `Uri.BuildQueryString` function is a powerful tool for building query strings that can be used in web scraping and data retrieval scenarios. By understanding the M code behind this function, it is possible to customize its behavior and build more complex query strings that meet specific requirements.

Power Query and M Training Courses by G Com Solutions (0800 998 9248)

Upcoming Courses

Contact Us

    Subject

    Your Name (required)

    Company/Organisation

    Email (required)

    Telephone

    Training Course(s)

    Your Message

    Upload Example Document(s) (Zip multiple files)