How to set the body of a http post request in Matlab - matlab

I'm trying to post to a restful service with Matlab. I've tried using webread, webwrite, and urlread and I cannot figure out how to set the body of the message.
My body is json and looks like this:
{"Item1": "string1", "Item2": "string2"}

I found out what I was doing wrong. I was constructing my body as a string literal and not as a matlab struct. Correct way:
api = 'http://myurl.net';
url = [api, '/Login'];
[un, pw] = GetAuthentication;
input = struct('Username',un,'Password',pw);
opts = weboptions('MediaType','application/json');
userInfo = webwrite(url, input, opts);

Related

How to connect to Webservice REST with POST from Power BI

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

How to mock response.readEnity(String.class), passing mock Response object

I want to mock response with payload as a simple string.
Below code is in my test :
Response response = mock(Response.class, RETURNS_DEEP_STUBS);
when(mockRestClient.get("someMockUrl")).thenReturn(response);
when(response.readEntity(String.class)).thenReturn("XXXYYYZZZ");
Also tried with:
Response response = Response.status(Status.OK).entity("XXXYYYZZZ").build();
MyCode looks something like this :
Response response = restClient.get(tokenUrl); // I was mocking this and getting mock response
String requestToken = response.readEntity(String.class); //failing at this line
None of the above is working.
Help is Appreciated!
I see the issue was with using the deep stubs. It was not necessary in my case.
Response mockResponse = mock(Response.class);
when(mockResponse.readEntity(String.class)).thenReturn("XXXYYYZZZ");

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);

Sending data to Firebase from Matlab

I want to save data to firebase from Matlab. Does firebase have similar api calls like ThingSpeak? How can i send JSON data from matlab by making API calls?
I am making API calls from Matlab like for JSON:
Firebase_Url = 'https://ecgproject-86945.firebaseio.com/';
writeApiKey = '***';
data = ['api_key=',writeApiKey,'&name=',"JSOpn9ZC54A4P4RoqVa"];
response = webwrite(Firebase_Url,data)
%data = struct('api_key',writeApiKey,'field1',data); //also tries this
%options = weboptions('MediaType','application/json');
The Error:
Error using readContentFromWebService (line 46)
The server returned the status 405 with message "Method Not Allowed" in response to the
request to URL https://ecgproject-86945.firebaseio.com/.
Error in webwrite (line 139)
[varargout{1:nargout}] = readContentFromWebService(connection, options);
Error in Untitled (line 16)
response = webwrite(Firebase_Url,data)
From reading the mathworks documentation on webwrite you need to use the two-parameter version of the method, passing in the additional information inside the second, data object:
data = ['api_key=',writeApiKey,'&name=',"JSOpn9ZC54A4P4RoqVa"];
response = webwrite(FirebaseURL,data)
Okay I found the solution apparently i didn't add .json at the end of the URL. Thank You. Here is the solution:
Firebase_Url = 'https://***.firebaseio.com/Channel1.json';
response = webwrite(Firebase_Url,'{ "first": "Jack", "last": "Sparrow" }')

Rest Assured API testing - Pass a Json Object as parameter to a get request

REST Assured Testing -
How to use delete request to delete the Workspace from this url
http://in-kumaran2-1:8080/devops-workbench-web/rest/api/workspace/delete/{projectId}
given the request
given().when().delete(url,JSON body);
Where Sample Request JSON body is given below
{"name":"newworkspace","workspaceFlow":"Open
Sorce","versionControl":"SVN","featureManagement":"JIRA","defectManagement":"","buildAutomation":"Selenium","deploymentAutomation":"","buildRepository":"Nexus","codeQualityTools":"SonarQube","automatedTestingTools":"Selenium","environmentProvision":"Puppet","environmentConfiguration":"Puppet","projectId":{"id":"56cebe578850d51c6fe07684","name":"wbproject","description":"wbproject","processTemplate":"Agile","projectManager":"Anil","projectStartDate":1454284800000,"projectEndDate":1475193600000,"remarks":null,"accountId":{"id":"56cebe218850d51c6fe07683","accountName":"workbench","accountDescription":"workbench
account"}}}
projectID has another Object {"id": "56cebe578850d51c6fe07684" ....} How to pass this projectId in the delete Request
actually, i have passed json object like below:
Response res =given().
content(jo). //jo is the json object to pass with the url.
with().
contentType("application/json").
header("Content-Type", "application/json").
when().
post(settings.getApiUrl()); //this is the url, i use post method
and jo is something like this:
JsonObject jo = new JsonObject();
jo.addProperty("username", "abc");//key and value
jo.addProperty("password", "abc");//key and value
u may try something like this.i used here as header u may send it as param.
URL is: http://example.com/building
My Query Strings are :
globalDates:{"startMs":1473672973818,"endMs":1481448973817,"period":90}
limitTo:6
loadTvData:true
startFrom:0
userId:5834fb36981baacb6a876427
Way to pass Query String Parameters in GET url using Rest Assured like this :-
when() .parameter("globalDates","startMs","1474260058054","endMs","1482036058051","period","90")
.parameters("limitTo","6")
.parameters("loadTvData","true")
.parameters("startFrom","0")
.parameters("userId","5834fb36981baacb6a876427");