Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

Convert Python Request to Microsoft Power BI M code

I would like to convert a request from Python code to M used in Power BI Power Query

My Python code is

\

import requests import datetime as dt

headers = {'Authorization': 'Bearer tok_123', 'Accept': 'text/csv'}

url = 'https://api.123/'

params = ( ('start_time', start_date), ('end_time', tomorrow), )

response = requests.get(url, headers=headers, params=params)

data = response.text

\

The M code I have made (which does not work) is below. Could you let me know where I am going wrong?

Am getting error 400 invalid request. I think there is something wrong with the way I am translating params.

\

let

apiUrl = "https://api.123/", ????? options = [Headers =[#"Authorization"="Bearer tok_123", #"start_time"="2021-01-05", #"end_time"="2021-02-05"]], ????? result = Web.Contents(apiUrl , options)

in

?????result

\

Thanks

question from:https://stackoverflow.com/questions/66065738/convert-python-request-to-microsoft-power-bi-m-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am getting a 400

See the sections below, "verifying request", and "error code details"

Without your url, or the docs, I don't know what endpoint you're using, so here's an example

HTTP GET https://www.example.com/api/user/search?limit=1000&region=US

Using RelativePath and Query

Note: It's important to use options[RelativePath] and options[Query] to prevent service refresh errors on the service. Check out docs: Web.Contents

let 
    Headers = [
        Accept="application/json"
    ],
    BaseUrl = "https://www.example.com",
    Options = [
        RelativePath = "/api/user/search",
        Headers = Headers,
        Query = [
            limit = 1000,
            region = "US"                    
    ],
    Response = Web.Contents(BaseUrl, Options),
    Result = Json.Document(Response) // skip if it's not JSON
in
    Result

Authorization

Setting options[ApiKeyName]lets you specify your API token / password using the credential store instead of in the code itself.

Otherwise you can set it using the Headers record just like you are in python.

Error Code details

For details, first specify the HTTP Status codes you want to handle

Options = [
    // add this param to Options
    ManualStatusHandling = {"400"}
]

Then view error details in the metadata

details = Value.Metadata(Response)

Verifying Request

You can view the actual HTTP requests fired by either using


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...