MS Power Query Looping MS Power Query Looping json json

MS Power Query Looping


Use List.Generate to pull the data until the next token is null.

List.Generate(initial as function, condition as function, next as function, optional selector as nullable function) as list

Code with explanations (untested as I can't access the API):

let    // Helper function to get results and next token.    get = (url as any, headers as any) as record =>        let            source = Json.Document(Web.Contents(url, headers)),            results = try source[results] otherwise null,            next = try source[_metadata][next] otherwise null,            return = [results=results, next=next]        in            return,    url = "https://api.automatic.com/trip/",    headers = [Headers=[#"Authorization"="Bearer XXX"]],    // Returns a list of lists of records.    return =         List.Generate(            // Initial value.            ()=> get(url, headers),            // If condition is true select (make a list) the result.            each [results] <> null,            // Generate the next list if condition is true.            each get([next], headers),            // Return (select) only [results].            each [results])in    return

Understanding what the each keyword does helps:

The each keyword is used to easily create simple functions. “each ...” is syntactic sugar for a function signature that takes the parameter “() => ...”

Each is useful when combined with the lookup operator, which is applied by default to For example, each [CustomerID] is the same as each _[CustomerID], which is the same as (_) => _[CustomerID]