How to connect to Webservice REST with POST from Power BI - rest

I am trying to connect to a webservice through Power BI but I still do not achieve result, first try to use the Web data source and with the Advanced Use add the Header that in my case is Content-Type and its value is application/json and additional as Body I have a token
Where I get as a result the following:
Additional also try to use as source "Blank Query", where I accessed the advanced editor section and add the following Query:
I get as an error the following:
To make sure that the Webservice works correctly and obtains a result I have used the Advanced REST Client tool and I have made the following configuration:
Where you can see that the Headers section I have added the Header name Content-Type and the value of the Header Value is application/json, in the Body section is where I have added the token
With this I realize that my Webservice gets an answer and that the service is working correctly, I would like someone to give me a little guidance in a short time to perform correctly

Supply the content to switch the method from GET to POST eg
Perform a POST against a URL, passing a binary JSON payload and
parsing the response as JSON.
https://learn.microsoft.com/en-us/powerquery-m/web-contents#example-2
let
url = "https://postman-echo.com/post",
headers = [#"Content-Type" = "application/json"],
postData = Json.FromValue([token = "abcdef"]),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response),
json = jsonResponse[json]
in
json
or
let
url = "https://postman-echo.com/post",
headers = [#"Content-Type" = "application/json"],
postData = Text.ToBinary("{ ""token"":""abcdef""}"),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response),
json = jsonResponse[json]
in
json

Related

Add flag to UnityWebRequest

I am trying to make a POST request to webpage that expects the --data field to be filled with some data to be processed. I'm pretty much trying to recreate this curl request, but with UnityWebRequest.
curl -X POST http://localhost:8000/clic/say?text=Make+the+gene+set --data '{"geneSetMembers":["UST"],"geneSetName":"selection0"}'
The UnityWebRequest documentation mentions that GET requests don't set any flags other than the url, but it's not clear if no other custom options exist for posts. Is there some way to format a WWWform or something that will hold the data such that the server will recognize it?
var form = new WWWForm();
// some way to plug in the jsonified data to the form
webRequest = UnityWebRequest.Post(url + route + to_say, form);
webRequest.downloadHandler = new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SendWebRequest();
// etc etc
I've tried just giving the form a field named "data" a la
form.AddField("data", "{ \"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}");
but the server does not like it, saying it "got error Invalid JSON literal name: data" So clearly that's the wrong syntax for it
EDIT: put lines in the same order they were in original code. Sorry, I have commented lines between them
Maybe your server doesn't like to receive the data as a field called data.
This ofcourse depends totally on the PHP code we don't see since you didn't share that part. b
But at least I can tell you that --data or also simply -d in curl refer to the entire data section and is not a field called data.
You could try to instead use a MultiPartFormDataSection passing just the data itself without a specific field name
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var form = new List<IMultiFormPart>{ new MultiPartFormDataSection(data) };
webRequest = UnityWebRequest.Post(url + route + to_say, form);
yield return webRequest.SendWebRequest();
which is now sent as content-type multipart/form-data though ...
Another alternative if your server really needs to receive a content-type application/json might be to "manually" compose the request e.g. like
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var request = new UnityWebRequest(url + route + to_say, "POST");
var bodyRaw = Encoding.UTF8.GetBytes(data);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
Though of you look close now this seems actually not to be the case since if you read the man curl
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded
which is actually exactly the default content type used by the simple string version of UnityWebRequest.Post.
So thinking about it it should actually be as simple as using the pure string version of UnityWebRequest.Post:
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var request = UnityWebRequest.Post(url + route + to_say, data);
yield return request.SendWebRequest();

Verify API Response

Am getting the response of a request like this:
var response = command.PostCommand(testCommand);
I will like to validate that the response is in a json format so am doing it like this:
Assert.AreEqual("application/json", response.ContentType);
Is this way correctly or do i need to specifically validate it from the content-type header response?
You can use the IRestRequest.OnBeforeDeserialization callback to check the response content type before it gets deserialised:
var request = new RestRequest(url)
.AddQueryParameter(x, y); // whatever you need to configure
request.OnBeforeDeserialization =
response => CheckContentType(response.ContentType);
await client.PostAsync<MyResponse>(request);

REST Hammock not adding content to post body

I've been fiddling a POST request that isn't working. What I've found is that the content of the request is empty even though I believe I'm adding it correctly (even though there aren't any docs available that I can find).
var json = JsonConvert.SerializeObject(payload);
var client = new RestClient
{
Authority = "",
Credentials = OAuthCredentials.ForProtectedResource(Registration.ClientKey,
Registration.ClientSecret,
AuthorizationToken.Token,
AuthorizationToken.Secret),
Method = WebMethod.Post,
Path = url
};
var request = new RestRequest();
request.AddHeader("Accept", ContentType);
request.AddHeader("Content-Type", ContentType);
request.AddPostContent(Encoding.UTF8.GetBytes(json));
response = client.Request(request);
I'm not having any trouble with authorization. I just kept getting a 400 error. After capturing the request with Fiddler, I noticed that content-length was 0. What am I missing? Do I need to do something in addition to AddPostContent? When I check the request object right before executing, there is content in PostContent, but it's as if Hammock isn't adding it to the request. I am using the latest full nuget (not ClientProfile).

How to add a http header when post request to a servicestack web api using servicestack swift plugin?

First below is a very straightforward code that post a req to the api.
let req = PurchaseRequest()
req.cellphone = "5101111111"
req.amount = 6
let client = JsonServiceClient(baseUrl: "http://example.com/webapi")
let response = try! client.post(req)
Now, how do I add a Http header to the request? For example, there is a http header called "Authorization" and we usually use this header to provide token, to authenticate users. How do I do that?
let client = JsonServiceClient(baseUrl: "http://example.com/webapi")
client.requestFilter = { (req:NSMutableURLRequest) in
req.addValue("FJEUJFJSKEJF#$"/*a token value*/, forHTTPHeaderField: "Authorization")
}
So I found the property called requestFilter of the jsonserviceclient, which I can then get the standard nsmutableurlrequest so the rest is easy, just plain old swift code, where I just add my token value to the Authorization http header. My code is doing exactly that.

Azure encoding job via REST Fails

I am trying to upload a video and encode it via azure rest service.
I have now hit the step of encoding the video but I am having difficulties with the request.
The following code shows my request:
var joburl = res.RequestMessage.RequestUri + "Jobs";
client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("x-ms-version", "2.8");
client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("x-ms-date", date);
//accept
t = new NameValueHeaderValue("odata", "verbose");
type = new MediaTypeWithQualityHeaderValue("application/json");
type.Parameters.Add(t);
client.DefaultRequestHeaders.Accept.Add(type);
result = await client.PostAsync(joburl,json);
the url:https://wamsamsclus001rest-hs.cloudapp.net/api/Jobs
the json:
{"Name":"khgfiuydencodingjob","InputMediaAssets":[{"__metadata":{"Uri":"https://wamsamsclus001rest-hs.cloudapp.net/api/Assets('nb%3acid%3aUUID%3ad037b321-cd1c-43a9-9607-c4910fa7a85b')"}}],"Tasks":[{"Configuration":"H264 Adaptive Bitrate MP4 Set 720p","MediaProcessorId":"nb:mpid:UUID:1b1da727-93ae-4e46-a8a1-268828765609","TaskBody":"<?xml version=\"1.0\"encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"}]}
The bearer token works as I use it for other request.
But I get a bad request 400 with the followin error message:
{"error":{"code":"","message":{"lang":"en-US","value":"Parsing request content failed due to: Make sure to only use property names that are defined by the type"}}}
Can anyone spot the error.
Thank you for the help
Okay I got it to work. Needed a odata=verbose in my json/string content - like this:
var jobInJson = JsonConvert.SerializeObject(job);
json = new StringContent(jobInJson, Encoding.UTF8);//,
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
I tried this earlier however I got a error 500 but now it is working.