I need to send cURL request to an api but i don't understand the documentation properly. First time working with cURL. Here is the details written to send request.
# Steps to send request
# First get JSON Web Token
# Please get your Client Id and Client Secret from https://dashboard.groupdocs.cloud/applications.
# Kindly place Client Id in "client_id" and Client Secret in "client_secret" argument.
curl -v "https://api.groupdocs.cloud/connect/token" \
-X POST \
-d "grant_type#client_credentials&client_id#xxxx&client_secret#xxxx" \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: application/json"
$ cURL example to join several documents into one
curl -v "https://api.groupdocs.cloud/v1.0/parser/text" \
-X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Authorization: Bearer
<jwt token>" \
-d "{
"FileInfo": {
"FilePath": "words\docx\document.docx",
}
}"
This is how the response will come
{
"text": "First Page\r\r\f"
}
Curl is just a tool for sending requests
you can do the same with http package in flutter
your first request with curl is equivalent to this
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var request = http.Request('POST', Uri.parse('https://api.groupdocs.cloud/connect/token'));
request.bodyFields = {
'grant_type': '',
'client_id': '',
'client_secret': ''
};
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
second request
var headers = {
'Authorization': 'Bearer <jwt token>',
'Content-Type': 'application/json'
};
var request = http.Request('POST', Uri.parse('https://api.groupdocs.cloud/v1.0/parser/text'));
request.body = json.encode({
"FileInfo": {
"FilePath": "words\\docx\\document.docx"
}
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
learn about http request , use a tool like postman to get used to it and then use http to send those requests
Related
I trying to write a google script to query Jira Tempo worklogs.
This is what I have so far:
function postDataForAPI() {
var payloadData = {
"taskKey" : []
};
payloadData.taskKey.push("AA-123");
var payload = Utilities.jsonStringify(payloadData);
var url = "https://api.tempo.io/core/4/worklogs/search";
var digestfull = PropertiesService.getUserProperties().getProperty("digest"); //get username and password (base64 encrypted)
var options = { "Accept":"application/json",
"Content-Type":"application/json",
"method": "POST",
"headers": {"Authorization": digestfull},
"muteHttpExceptions": true,
"payload" : payload
};
var resp = UrlFetchApp.fetch(url,options);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
return "";
}
else {
return resp.getContentText();
}
}
When I execute the above it fails.
If I use curl then I can successfully make the request (I think this is essentially the same POST):
curl -u "username:password" -X POST https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search -H 'Content-Type: application/json' -d '{"taskKey":["AA-123"]}'
Making GET requests against the same API works fine:
function getDataForAPI() {
var url = "https://api.tempo.io/core/4/worklogs/101112";
var digestfull = PropertiesService.getUserProperties().getProperty("digest"); //get username and password (base64 encrypted)
var options = { "Accept":"application/json",
"Content-Type":"application/json",
"method": "GET",
"headers": {"Authorization": digestfull},
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url,options);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
return "";
}
else {
return resp.getContentText();
}
}
So I'm confident it is not Authorisation (GET request succeeds). The curl request succeeds and appears to be in the same form as the google script and yet the google script POST fails.
What do I have wrong?
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl -u "username:password" -X POST https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search -H 'Content-Type: application/json' -d '{"taskKey":["AA-123"]}'
Modification points:
It seems that "Accept":"application/json" is not used in the sample curl command.
"Content-Type":"application/json" is required to be included in the request header. But, at UrlFetchApp, the property of contentType can be used.
Utilities.jsonStringify has been deprecated. Ref
When these points are reflected in your script, it becomes as follows.
Modified script:
function postDataForAPI() {
var payloadData = { "taskKey": [] };
payloadData.taskKey.push("AA-123");
var url = "https://api.tempo.io/core/4/worklogs/search";
var digestfull = PropertiesService.getUserProperties().getProperty("digest");
var options = {
"method": "POST",
"contentType": "application/json",
"headers": { "Authorization": digestfull },
"muteHttpExceptions": true,
"payload": JSON.stringify(payloadData)
};
var resp = UrlFetchApp.fetch(url, options);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
return "";
}
else {
return resp.getContentText();
}
}
Note:
When I saw your provided curl command, it seems that the URL is different. The sample curl command uses https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search. But your script uses https://api.tempo.io/core/4/worklogs/search. I'm worried about this difference. So if the above-modified script didn't work, please check the URL again.
The request of this modified script is the same as the sample curl command. But if an error occurs, please check each value like digestfull and payloadData, again.
Reference:
fetch(url, params)
My coding knowledge is pretty shaky because I didn't learn it orderly.
Right now, I am trying to send an cURL Request and the documentation is:
curl https://api.at356.com/studio/v1/sd-large/complete
-H 'Content-Type: application/json'
-H 'Authorization: Bearer YOUR_API_KEY'
-X POST
-d '{"prompt": "Life is like",
"numResults": 1,
}'
this is the code
function searchFor(query) {
// Base URL to access
var urlTemplate = "https://api.at356.com/studio/v1/sd-large/complete "
// Script-specific credentials & search engine
var ApiKey = "shwMCMgEviwfz6X7Rvbtna6";
var prompt = {
"prompt": query,
"numResults": 1,
}
// Build custom cURL
var cURL = {
'method': 'POST',
"headers":{
"Content-type": "application/json",
"Authorization": ApiKey,
},
prompt,
"muteHttpExceptions": true,
"followRedirects": true,
"validateHttpsCertificates": true
};
// Perform Request
//Logger.log( UrlFetchApp.getRequest(urlTemplate, params) ); // Log query to be sent
var response = UrlFetchApp.fetch(urlTemplate, cURL,);
var respCode = response.getResponseCode();
if (respCode !== 200) {
throw new Error("Error " + respCode + " " + response.getContentText());
} else {
// Successful search, log & return results
var result = JSON.parse(response.getContentText());
Logger.log("Obtained %s search results in %s seconds.",
result.searchInformation.formattedTotalResults,
result.searchInformation.formattedSearchTime);
return result;
}
}
Can anyone tell me what I'm doing wrong and how to fix it
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl https://api.at356.com/studio/v1/sd-large/complete \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-X POST \
-d '{"prompt": "Life is like", "numResults": 1, }'
You have already confirmed that your this curl command works fine.
Modified script:
var query = "###"; // Please set the value.
var ApiKey = "###"; // Please set your API key.
var url = "https://api.at356.com/studio/v1/sd-large/complete";
var prompt = {
"prompt": query,
"numResults": 1,
};
var params = {
"method": "POST",
"headers": { "Authorization": "Bearer " + ApiKey },
"contentType": "application/json",
"payload": JSON.stringify(prompt),
"muteHttpExceptions": true,
};
var response = UrlFetchApp.fetch(url, params);
console.log(response.getContentText());
Note:
From your sample curl command, Authorization is like -H 'Authorization: Bearer YOUR_API_KEY'. So I modified to "headers": { "Authorization": "Bearer " + ApiKey }. If your actual API key is like Bearer ###, please modify this to "headers": { "Authorization": ApiKey }.
Reference:
fetch(url, params)
I have the below script, that is returning a 400 - bad request.
function createIssue(e)
{
var url = "https://jira.xxxx.com/rest/api/2/issue/";
var data = {'fields': {
'project': {'key':'DWH'},
'summary':'Resttest',
'description':'test',
'issuetype':{ 'name': 'Data Requests'},
'components':[{ 'name':'Data Warehouse'}],
'fixVersions':[{ 'name':'NA'}] }};
var payload = JSON.stringify(data);
Logger.log(payload);
var headers =
{
'content-type': 'application/json',
'Accept': 'application/json',
'authorization': 'Basic xxxxxxxxxxxxxx'
};
var options =
{
'content-type': 'application/json',
'method': 'POST',
'muteHttpExceptions' : true,
'headers': headers,
'payload': payload
};
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
var responseText = response.getContentText();
var dataAll = JSON.parse(response.getContentText());
var issueKey = dataAll.key
Logger.log(dataAll)
}
I have tested out the actual payload via cURL and it was working, so Is there something else I am missing with this script?
Thanks a million for any assistance.
Best,
Neil
EDIT:
The curl command :
curl -D- -H
"Authorization: Basic xxxxxxxxxxxx1bXBraW5zMDQh" -X POST --data
"{ """fields""": { """project""": { """key""": """DWH""" }, """summary""":
"""REST test 11111.""", """description""": """test""", """issuetype""": {
"""name""": """Data Requests""" }
,"""components""":[{ """name""":"""Data Warehouse"""}] , """fixVersions""":
[{"""name""":"""NA"""}]} }" -H "Content-Type: application/json"
https://jira.xxxxxxxxx.com/rest/api/2/issue/
I was doing some further reading and it appears that the google apps scripts are run from the google servers. My jira instance is behind a company intranet, and as such not accessible from googles servers. I also note a useIntranet feature that is depreciated. Is there any way around this?
Many thanks,
Neil
When I am using curl command or Postman I am getting proper response within 1 sec but request module is going into timeout most of the time, pls help.
I think I need to add code for -c cookie.txt -b cookie.txt'
curl https://example.com/cmd -H "Content-Type:application/json" -k -d '{"cmd":{"dlpktenc":{"id":0,"byte0":001,"byte1":532}}} -c cookie.txt -b cookie.txt'
request module:
var request = require('request');
request = request.defaults({jar: true});
request(
{ method: 'POST',
uri: 'https://example.com/login',
form:
{ user: username,
password: password
},
rejectUnauthorized: false,
},
function( err, res, body ){
if (!err){
console.log(JSON.parse(body));
var requestData = {"cmd":{"dlpktenc":{"id":0,"byte0":001,"byte1":532}}};
request(
{ method: 'POST',
uri: 'https://example.com/cmd',
header:{
'content-type': 'application/json',
},
json: requestData,
rejectUnauthorized: false
},
function( err, res, body ){
if (!err){
console.log(body);
} else console.log(err);
});
} else console.log(err);
});
In cURL, -d means (from the man pages, emphasis mine):
-d, --data
(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. Compare to -F, --form.
...
See also --data-binary and --data-urlencode and --data-raw. This
option overrides -F, --form and -I, --head and --upload.
If curl is working with the command you said, you need to send your request the same way:
request({
method: 'POST',
uri: 'https://example.com/cmd',
header: {
// Correct content type
'content-type': 'x-www-form-urlencoded',
},
body: requestData,
rejectUnauthorized: false
},
function(err, res, body) {
if (!err) {
console.log(body);
} else console.log(err);
}
);
There is a problem in sending the body in the request module as an object unless the json option is set as true
var requestData = {
"cmd": {
"dlpktenc": {
"id": 0,
"byte0": 001,
"byte1": 532
}
}
};
request({
method: 'POST',
url: 'http://localhost:9007/mbe',
header: {
'content-type': 'application/json',
},
body: requestData,
rejectUnauthorized: false,
//THE NEXT LINE WAS MISSING IN YOUR CODE
json : true
},
function(err, res, body) {
if (!err) {
console.log(body);
} else console.log(err);
}
);
I am trying to execute a POST request over JSON-RPC on my NodeJS server. Converting the following curl command:
curl -X POST --data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' http://localhost:8545
In NodeJS I keep receiving:
200 {"id":-1,"jsonrpc":"2.0","error":{"code":-32600,"message":"Could not decode request"}}
In the header I am specifying the Content-Type. If someone can point out what I am not specifying and how to add it in it would be much appreciated.
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json-rpc',
'Accept':'application/json-rpc'
}
var options = {
url: "http://localhost:8545",
method: 'POST',
headers: headers,
form: {"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":1}
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.writeHeader(200, {"Content-Type": "text/plain"});
res.write(res.statusCode.toString() + " " + body);
}else{
res.writeHeader(response.statusCode, {"Content-Type": "text/plain"});
res.write(response.statusCode.toString() + " " + error);
}
res.end();
})
form is for application/x-www-url-encoded requests, not JSON. Try these options instead:
var options = {
url: "http://localhost:8545",
method: 'POST',
headers: headers,
body: JSON.stringify({
jsonrpc: '2.0',
method: 'personal_newAccount',
params: ['pass'],
id: 1
})
}
You can also set json: true in your options to have request automatically parse the response as JSON.
You're missing the --header option:
curl --request POST \
--header 'Content-type: application/json' \
--data '{"jsonrpc":"2.0","method":"personal_newAccount","params":["pass"],"id":74}' \
http://localhost:8545
To use "personal_newAccount" and the rest options from Ethereum Docs you need to start the server with the needed API's:
--rpcapi "personal,eth,web3"