POST command to WebCeo API - api

Trying to connect to this WebCEO API.
function getProjects() {
var payload = {
"key": "CUSTOMER_KEY",
"method": "get_projects"
};
payload = JSON.stringify(payload);
var url = "https://online.webceo.com/api/";
var options = {
"method": 'POST',
"contentType" : "application/json",
"payload": payload
};
var response = UrlFetchApp.fetch(url, options);
}
Receiving "Request failed for https://online.webceo.com/api/ returned code 404".
Any hint on what else I need to include / change?

Body must contain the following:
json={"key": "YOUR_API_KEY", "method": "get_projects"}

Well, https://online.webceo.com/api/ does return a 404 when you just try to access it. Did you manage to get that page to not return a 404 error from another client?
Doing so will probably tell you what you're missing here.
However, I'd suspect their API might be having issues.

That's true, you don't make a GET request. You have to send parameters in the body of a POST request. Below is an example in CURL for a situation when you need to get the list of projects:
curl -X POST -d 'json={"key": "YOUR_API_KEY", "method": "get_projects" }' https://online.webceo.com/api/

Related

Saving a Postman collection variable from he response body

Trying to figure out why I cannot get this to work? Also, console does not give much of a result.
Scenario:
Making the POST request to get the response with TOKEN
Save the response token to collection variable (as the collection file will be used for importing to another testing solution in the cloud)
Using that collection variable to log out from the session
So, I need to be able to store this as a collection variable and use that token when logging out from the session/DELETE the API admin session.
Error in the console:
There was an error in evaluating the test script: JSONError: Unexpected token 'o' at 1:2 [object Object] ^
Tests:
var response = pm.response.json()
var jsonData = JSON.parse(response)
pm.collectionVariables.set("token", jsonData.response.token);
Response body:
{
"response": {
"token": "***"
},
"messages": [
{
"code": "0",
"text": "OK"
}
]
}
Thank you very much for any advice!
JSON.parse(responseBody) always gets a json representation of the response.
A complete fail safe approach would be:
pm.test("response is ok", ()=>{
pm.response.to.have.status(200)
})
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);
Here's the approach i used.
Send the request
Check if there response is 200
If it's true set the token
pm.test("response is ok", ()=>{
if( pm.response.to.have.status(200)){
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);
}
})
You need to change your status code depending on the condition.
Hope it helps

REST API request Flutter web CORS issue

I hope you are well
I have a problem with flutter web. I try to make an API REST request to https://timeapi.io/api/TimeZone/zone?timeZone=Europe/Amsterdam to get the time from a specific location but I get this error XMLHttpRequest error and when displaying the console in the browser, I get this error (image below)
After a few days of research, I know that it is CORS and I was able to test a few solutions but without success.
Here is what I could do:
Future<void> _getCurrentDateTime() async {
try {
var url = Uri.https('timeapi.io', 'TimeZone/zone', {'timeZone': 'Europe/Amsterdam'});
final headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, DELETE",
"Origin": "https://localhost"
};
var response = await http.get(url, headers: headers);
log('Response status: ${response.statusCode}');
log('Response body: ${response.body}');
// return now;
} catch (e) {
rethrow;
}
}
How to solve this error? Thanks
You are missing /api/ as part of the url in line:
var url = Uri.https('timeapi.io', 'TimeZone/zone', {'timeZone': 'Europe/Amsterdam'});
If you notice the error on your console you will see that the URL that is printed is also missing the api in the URL.
Which in turn ends up in a 404, if you open https://timeapi.io/TimeZone/zone?timeZone=Europe/Amsterdam in the browser you'll find a 404 response.
Thus, the 404 doesn't contain CORS headers in the response, resulting in the CORS error you see on the browser console.
If you want to call https://timeapi.io/api/TimeZone/zone?timeZone=Europe/Amsterdam
The code should probably be
var url = Uri.https('timeapi.io', 'api/TimeZone/zone', {'timeZone': 'Europe/Amsterdam'});
Also, you may want to remove these headers as they're supposed to be sent from the backend and not the frontend. The following lines of code are redundant.
final headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, DELETE",
"Origin": "https://localhost"
};

Request body missing from POST requests made using Postman scripting

I am trying to run a pre-request script for authenticating all my requests to the Spotify API. It works via the Postman GUI, but when I try to make the request via scripting, it fails because there is no body. Here is my code
const postRequest = {
url: pm.environment.get("spotifyAuthApi"),
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "*/*",
"Content-Length": 29,
"Authorization": "Basic " + btoa(pm.environment.get("client_id") + pm.environment.get("client_secret"))
},
body: {
grant_type: "client_credentials",
}
}
I get a
error: "unsupported_grant_type"
error_description: "grant_type parameter is missing"
And when I examine the request via the postman console, there is no request body, even though the request was built exactly like my fetch token request that does the same thing successfully in postman, only via the GUI instead of via a pre-request script. I have searched far and wide about this issue and tried multiple variations of the body object but to no avail. Either the body object doesn't generate my desired field, or it doesn't get created at all.
Mode might be missing in the body object. Try this:
body: {
mode: 'raw',
raw: JSON.stringify({ grant_type: 'client_credentials' })
}
More details might be found in Postman docs for RequestBody.
If you're using urlencoded, the body of the request would be structured like this:
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'grant_type', value: 'client_credentials'}
]
}

cannot subscribe to onedrive API

I tried to subscribe to onedrive webhooks by hitting
https://graph.microsoft.com/v1.0/subscriptions
https://graph.microsoft.com/beta/subscriptions
parameters are:
"changeType": "created,updated,deleted",
"notificationUrl": url.
"resource": "me/drive/root",
"clientState": "client-specific string",
"expirationDateTime": "2018-01-01T11:23:00.000Z",
I am getting an error like below:
{ error:
{ code: 'InvalidRequest',
message: 'Server could not process subscription creation payload.',
innerError:
{ 'request-id': 'id',
date: '2018-10-16T09:16:46' } } }
I am trying it in my local.
Is there any solution ?
Make sure you post a json request, that means:
Request body is a json string;
'Content-Type' field in headers, and value is 'application/json'
If you use Python, there is a shortcut:
import requests
url = "https://graph.microsoft.com/beta/subscriptions"
headers = {'Authorization': 'Bearer ' + "YOUR_TOKEN"}
data = {
"changeType": "created,updated,deleted",
"notificationUrl": url.
"resource": "me/drive/root",
"clientState": "client-specific string",
"expirationDateTime": "2018-01-01T11:23:00.000Z"
}
resp = requests.post(headers=headers, json=data)
I had the same problem trying the request with Postman. The body was in x-www-form-urlencoded format. It worked when I changed the body format to raw and specified JSON.
Not working "x-www-form-urlencoded" format
Working "raw" format
It looks like MS Graph API only accepts certain input formats. Hope this will help!

Telegram Bot gets "Bad Request: message text is empty"

When my Telegram bot sends sendMessage to Telegram server it gets the error message:
{"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}
The problem appeared this morning, before that my bot worked a whole year without errors. GetUpdates command works well as before. I use GET HTTP method to send commads:
https://api.telegram.org/bot<MyToken>/sendMessage
with UTF-8-encoded data attached:
{"chat_id":123456789,"text":"any text"}
Has anyone encountered this?
If the issue still persists, try to modify your curl request. For me adding header
'Content-Type: application/json' and -d '{"chat_id":12309832,"text":"any text"}' fixed issue
Another way to send a message by emulating a form :
curl -s -X POST https://api.telegram.org/bot{apitoken}/sendMessage \
-F chat_id='-1234567890' -F text='test message'
Well, i wrote wrapper on C language to communicate via SSL with telegram bot api. SO now I can clearly answer questions about telegram API spec.
Problem number one
First of all if we are talking about raw queries we need to remember about specifications.
By default HTTP/HTTPS post requests should consists of:
<METHOD>[space]<PATH with only valid chars> <\r\n>
<HOST valid regexed\r\n>
<Content-type valid regexed><\r\n>
<Content-Length with length of your POST body data><\r\n>
<\r\n before body>
<body>
So, i tried to send raw queries with out Content-Length and i had error same as yours. That's the first problem.
Problem number two
By default if you trying to send non valid request with sendMessage method - telegram bot api will response with error same as yours. So, yeah, that's pretty tricky error to debug...
If you trying to send raw query, be sure that your JSON data is serialized nicely and there is no errors like shielding.
Summarizing
Request:
POST /bot<token>/sendMessage HTTP/1.1
Host: api.telegram.org:443
Connection: close
Content-Type: application/json
Content-Length: 36
{"chat_id":<integer>, "text":"test \\lol"}
Second backslash if shielding.
Code on C
sprintf(reqeustCtx.request,
"POST /bot%s/%s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s\r\n", bot_token, bot_method,
reqeustCtx.res_addr, strlen(body), body);
BIO_puts(bio, reqeustCtx.request);
BIO_flush(bio);
memset(reqeustCtx.response, '\0', BUFFSIZE);
read_bytes = BIO_read(bio, reqeustCtx.response, BUFFSIZE);
if (read_bytes <= 0) {
printf("No response");
exit(-1);
}
cert_free(cert_store, ssl_ctx, ca_cert_bio);
// free memory //
reqeustCtx.method(reqeustCtx.res_addr, reqeustCtx.request,
reqeustCtx.current_work_dir, reqeustCtx.current_cert);
/* json response, need to parse */
return reqeustCtx.response;
I got this error too.
I used sendMessage() method only with "low-level" Node https:
const https = require('https');
const data = JSON.stringify({
chat_id: config.telegram.chatId,
text: 'some ASCII text'),
});
const options = {
hostname: 'api.telegram.org',
port: 443,
path: `/bot${config.telegram.botToken}/sendMessage`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let chunks = [];
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => {
const resBody = Buffer.concat(chunks).toString('utf8');
if (res.statusCode === 200) {
console.log(`Message sent`);
} else {
console.error(`${res.statusCode} ${res.statusMessage} ${res.headers['content-type']}
${resBody}`)
}
});
});
req.on('error', (error) => {
reject(error)
});
req.write(data);
req.end();
And for ASCII text it was ok, however for some non-ASCII text I got:
const data = JSON.stringify({
chat_id: config.telegram.chatId,
text: 'Привет Мир!'),
});
Error:
400 Bad Request application/json
{"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}
In my case content length was calculated with invalid length 'Content-Length': data.length (invalid for Telegram?...), so I comment out this header and now it works for UTF-8!
headers: {
'Content-Type': 'application/json',
//'Content-Length': data.length
}
In my case, I was using curl_setopt($this->curl, CURLOPT_POSTFIELDS, json_encode($fields)); to post this json via sendMessage method:
{
"chat_id":000000000,
"text":"Choose one of the following options: ",
"reply_to_message_id":292,
"reply_markup":{
"keyboard":[
[
"Enable",
"Disable"
]
]
}
}
The problem was that when passing fields to the curl_setopt method, I was encoding the whole php array so I solved it by just encoding the reply_markup array which was a part of my json.
Try to put "Message" object with chat_id & text to HttpEntity in your restTemplate service, like below:
public MessageDto sendMessage(Message message) {
return restTemeplate.exchange(
"https://api.telegram.org/bot{token}/sendMessage",
HttpMethod.POST,
new HttpEntity<>(message, HttpHeaders.EMPTY),
MessageDto.class
).getBody();
}