Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Power Query Uri.BuildQueryString Function Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The Uri.BuildQueryString function in Power Query (M language) converts a record of field-value pairs into a single, URL-encoded query string. This is used primarily when constructing API requests where parameters must be passed after a question mark in the URL (e.g., ?key1=value1&key2=value2). Instead of manually concatenating strings and risking errors with special characters or spaces, this function automates the formatting and encoding process.

What You'll Need

  • Microsoft Excel or Power BI Desktop with Power Query installed.
  • Access to the Advanced Editor or a Custom Column dialog.
  • A record containing the parameters you wish to send to a web service.

Step-by-Step

  1. Open the Power Query Editor: In Excel, go to the Data tab and select Get Data > Launch Power Query Editor. In Power BI, click Transform Data on the Home ribbon.
  2. Define Your Parameters as a Record: The function requires a record as its input. You can create this manually in the Advanced Editor or by using a record variable. For example, if you need to filter a search by a city and a date, your record should look like this: .
  3. Insert the Function: If you are adding a custom column, go to the Add Column tab and select Custom Column. In the formula box, enter Uri.BuildQueryString([YourRecordColumn]). If you are working in the Advanced Editor, create a step such as QueryString = Uri.BuildQueryString(MyParameterRecord).
  4. Verify the Output: The function will return a text string. For the record , the output will be "City=New%20York&Date=2023-10-01" . Note how the space in "New York" is automatically converted to %20 .
  5. Combine with the Base URL: To make the string useful for a web request, concatenate it with your base API endpoint using the & operator. A typical implementation looks like: BaseUrl & "?" & Uri.BuildQueryString(MyParameterRecord).
  6. Pass to Web.Contents: Use the final combined string inside the Web.Contents function to execute the call. Example: Web.Contents(BaseUrl & "?" & Uri.BuildQueryString(MyParameterRecord)).

Common Mistakes

One of the most frequent errors is passing a table instead of a record to the function. Uri.BuildQueryString is strictly designed for records (denoted by square brackets []). If your parameters are currently in a table format (two columns: Key and Value), you must first convert that table into a record using Record.FromList or a similar transformation before the function will accept it.

Another common mistake is forgetting the question mark. The function generates the key-value pairs and the ampersands between them, but it does not provide the leading ? required by the HTTP protocol to signal the start of the query string. If you simply concatenate the base URL and the result of the function, the server will likely return a 404 error because it treats the parameters as part of the file path rather than query variables.

Users also often try to manually encode characters (like using Text.Replace to change spaces to %20) before passing the value to the function. This is redundant and can lead to "double encoding," where a character is encoded twice, resulting in a string the API cannot decode. Trust the function to handle the encoding of special characters automatically.

Tips

To make your queries dynamic, avoid hard-coding the record. Instead, create a separate "Parameters" table in your Power Query model. You can then convert a specific row of that table into a record. This allows users to change the API filters in the Excel sheet or Power BI parameter pane without ever opening the M code editor.

When dealing with complex APIs that require many optional parameters, create a record that contains all possible keys. Use Record.SelectFields to filter out null values before passing the record to Uri.BuildQueryString. This ensures that your URL remains clean and does not send empty parameters (like &category=) which some APIs might reject as invalid input.

For better readability in the Advanced Editor, break your URL construction into multiple steps. First, define the base URL; second, define the parameter record; third, generate the query string; and finally, combine them. This makes debugging significantly easier because you can click on each step in the Applied Steps pane to see exactly where a formatting error occurred.

Troubleshooting

If the function returns an error stating that it cannot convert the value to a record, check your brackets. Ensure you are using [Field="Value"] and not {Field="Value"}, as curly braces denote a list, not a record. If you are referencing a column from a previous step, ensure that the column's data type is set to Record.

If the API returns a "Bad Request" or "400" error, inspect the generated string in the Power Query preview. Check for trailing ampersands or missing keys. If the API requires specific casing (e.g., ApiKey instead of apikey), ensure the field names in your record match the API documentation exactly, as Uri.BuildQueryString preserves the casing of the record field names.

If you encounter issues with date formats, remember that Uri.BuildQueryString converts values to text using the default local format. If your API requires ISO 8601 format (YYYY-MM-DD), you must explicitly convert the date to text using Date.ToText([DateColumn], "yyyy-MM-dd") within the record before passing it to the function.

Frequently Asked Questions

Does Uri.BuildQueryString handle arrays?

No, it does not natively handle arrays or lists. If an API requires multiple values for one key (e.g., ?id=1&id=2), you cannot simply put a list in the record. You will need to manually construct that specific part of the string or use a custom function to repeat the key.

Is it better than manual string concatenation?

Yes, because it handles URL encoding. Manual concatenation fails when your parameters contain spaces, commas, or symbols like # or &, which would break the URL structure. This function ensures those characters are safely encoded.

Can I use this for POST request bodies?

While it creates a string that looks like a form-urlencoded body, Uri.BuildQueryString is intended for the URI (the address). For POST bodies, it is more common to use Json.FromValue to send data as a JSON object, depending on what the API expects.

What happens if a record value is null?

If a value in the record is null, the function typically includes the key but leaves the value empty (e.g., key=). To avoid this, filter out nulls from your record using Record.RemoveFields or a custom filtering step before calling the function.

Does this function work in Power BI Service?

Yes, it is a standard part of the M language engine. Once the query is published to the Power BI Service, the function will execute during the scheduled refresh just as it does in the Desktop version.