I've been trying to use curl to send requests but I keep getting an error:
Error: "" - Code: 3 (The URL was not properly formatted.)
Here is my code that I have been using (after successful authentication and using my access token)
$name = 'test' . rand();
$notes = 'hello hello' . rand();
// Curl request to create asana task.
$url = 'https://app.asana.com/api/1.0/tasks';
$header = "Authorization: Bearer $token";
$curl = curl_init();
curl_setopt($curl, array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'notes' => $notes,
'name' => $name,
'projects' => 'xxxxxxxxxxxxxxx',
),
));
curl_setopt($curl, CURLOPT_HTTPHEADER, array($header));
$result = curl_exec($curl);
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
Where I got the project id from the id in the URL of the project.
Update: the equvilant command line curl command I took from https://asana.com/developers/api-reference/tasks and is below. Running this is in the command line worked.
curl -H "Authorization: Bearer tokenid123" https://app.asana.com/api/1.0/tasks -d "notes=test notes" -d "projects[0]=xxxxxxxxxxxxxxx" -d "name=test"
Related
we're using GLPI API we need to create a ticket linked with documents .
The only curl part that i can't translate it's the document's upload .
With Curl (working) :
curl -i -X POST "http://glpitest/glpi/apirest.php/Document" -H "Content-Type: multipart/form-data" -H "Session-Token:sessiontoken"-H "App-Token:apptoken" -F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json" -F "filename[0]=#test.txt" "http://glpitest/glpi/apirest.php/Document"
But i can't translate this is in PHP CURL i tried something like this :
$headers = array(
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
'Http_Accept: application/json',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
echo $url = $_SESSION['api_url'] . "/Document";
$cfile = new CURLFile('testpj.txt', 'text/plain', 'test_name');
//$manifest = 'uploadManifest={"input": {"name": "test", "_filename" : "testpj.txt"}};type=application/json filename[0]=#'+$cfile;
$post = ["{\"input\": {\"name\": \"test\", \"_filename\" : \"testpj.txt\"}};type=application/json}", #"C:\\xampp\htdocs\glpi"];
print_r($post);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
the example in the api:
$ curl -X POST \
-H 'Content-Type: multipart/form-data' \
-H "Session-Token: 83af7e620c83a50a18d3eac2f6ed05a3ca0bea62" \
-H "App-Token: f7g3csp8mgatg5ebc5elnazakw20i9fyev1qopya7" \
-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}};type=application/json' \
-F 'filename[0]=#file.txt' \
'http://path/to/glpi/apirest.php/Document/'
< 201 OK
< Location: http://path/to/glpi/api/Document/1
< {"id": 1, "message": "Document move succeeded.", "upload_result": {...}}
update : I tried #hanshenrik but i have an error .
["ERROR_JSON_PAYLOAD_INVALID","JSON payload seems not valid"]
in the api.class.php :
if (strpos($content_type, "application/json") !== false) {
if ($body_params = json_decode($body)) {
foreach ($body_params as $param_name => $param_value) {
$parameters[$param_name] = $param_value;
}
} else if (strlen($body) > 0) {
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
$this->format = "json";
} else if (strpos($content_type, "multipart/form-data") !== false) {
if (count($_FILES) <= 0) {
// likely uploaded files is too big so $_REQUEST will be empty also.
// see http://us.php.net/manual/en/ini.core.php#ini.post-max-size
$this->returnError("The file seems too big!".print_r($_FILES), 400,
"ERROR_UPLOAD_FILE_TOO_BIG_POST_MAX_SIZE", false);
}
// with this content_type, php://input is empty... (see http://php.net/manual/en/wrappers.php.php)
if (!$uploadManifest = json_decode(stripcslashes($_REQUEST['uploadManifest']))) {
//print_r($_FILES);
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
I have no uploadManifest in $_REQUEST and if i put the the filename[0]file i have the curl error 26 (can't read file) .
Thank you
translating
-F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json"
is tricky because php doesn't really have native support for adding Content-Type headers (or any headers really) to members of a multipart request, with the only *exception* (known to me) being CURLFile's "Content-Type" and Content-Disposition's "filename" header... with that in mind, you can work around this by putting your data in a file and creating a CURLFile() around that dummy file, but it's.. tricky and stupid-looking (because PHP's curl api wrappers lacks proper support for it)
with the CURLFile workaround, it would look something like:
<?php
declare(strict_types = 1);
$ch = curl_init();
$stupid_workaround_file1h = tmpfile();
$stupid_workaround_file1f = stream_get_meta_data($stupid_workaround_file1h)['uri'];
fwrite($stupid_workaround_file1h, json_encode(array(
'input' => array(
'name' => 'Uploaded document',
'_filename' => 'test.txt'
)
)));
curl_setopt_array($ch, array(
CURLOPT_URL => "http://glpitest/glpi/apirest.php/Document",
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Session-Token:sessiontoken",
"App-Token:apptoken"
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => new CURLFile($stupid_workaround_file1f, 'application/json', ' '), // https://bugs.php.net/bug.php?id=79004
'filename[0]' => new CURLFile('test.txt', 'text/plain')
)
));
curl_exec($ch);
curl_close($ch);
fclose($stupid_workaround_file1h);
Thanks for the Help .
$document can be a $_FILES['whatever'] post .
Works on GLPI api .
<?php
declare (strict_types = 1);
session_start();
$document = array('name' => 'document', 'path' => 'C:\xampp\htdocs\glpi\document.pdf', 'type' => 'txt', 'name_ext' => 'document.pdf');
$url = $_SESSION['api_url'] . "/Document";
$uploadManifest = json_encode(array(
'input' => array(
'name' => $document['name'],
'_filename' => $document['name_ext'],
),
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data',
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => $uploadManifest,
'filename[0]' => new CURLFile($document['path'], $document['type'], $document['name_ext']),
),
));
print_r($_REQUEST);
echo $result = curl_exec($ch);
echo "erreur n° " . curl_errno($ch);
$header_info = curl_getinfo($ch, CURLINFO_HEADER_OUT) . "/";
print_r($header_info);
if ($result === false) {
$result = curl_error($ch);
echo stripslashes($result);
}
curl_close($ch);
I Have the following command I can run in PHP and it works as expected:
$params = [
'file' => $xmlLocalPath,
'type' => 'mismo',
'file_type' => $xmlFile['file_type'],
'filename' => $xmlFile['file_name']
];
$cmd =
'curl -X POST ' . $this->outboundBaseURL . 'document \
-H "Accept: application/json" \
-H "Authorization: Bearer ' . $this->token . '" \
-H "Cache-Control: no-cache" \
-H "Content-Type: multipart/form-data" \
-F "file=#' . $params['file'] . ';type=' . $params['file_type'] . '" \
-F "type=' . $params['type'] . '" \
-F "filename=' . $params['filename'] . '"';
exec($cmd, $result);
I need to get this to work using PHP's curl library, but I can't get it to work quite right. I'm on PHP 5.6, and here's what I have right now:
$params = [
'file' => $xmlLocalPath,
'type' => 'mismo',
'file_type' => $xmlFile['file_type'],
'filename' => $xmlFile['file_name']
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->outboundBaseURL . 'document',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $params,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Authorization: Bearer ' . $this->token,
'Cache-Control: no-cache',
'Content-Type: multipart/form-data'
]
]);
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$response = curl_exec($ch);
$err = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
I know the issue has to be with POSTFIELDS, and the file in particular, but I'm not show how to give PHP CURL the parameters in a proper way such that the file and other parameters will send just as the do in the raw curl call. I understand that the "#" method is deprecated in PHP Curl and I've also tried using curl_file_create with the local file with no success
Try adding one more parameter:
CURLOPT_POST => 1
I have to send a GET Request within a PHP Script to get data from an API with a certain given client-id without the usage of cURL.
In the terminal I use following command:
curl -i -u “123456-123ea-123-123-123456789:“-H “Content-Type:
application/json” -X GET
“https://api.aHoster.io/api/rest/jobboards/jobs”
(123456-123ea-123-123-123456789 in this command is the given client-id I got)
Everything works fine in the terminal, but now I like to do this GET request in a php script.
How do I add the client-id in this attempt?
<?php
$url = 'https://api.aHoster.io/api/rest/jobboards/jobs';
$client_id = '123456-123ea-123-123-123456789';
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'GET',
)
);
$context = stream_context_create($options);
$result = #file_get_contents($url, false, $context);
if ($http_response_header[0] == "HTTP/1.1 200 OK") {
//...
} else {
// ...
}
?>
Based on your cURL command you want to add an Authorization header:
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n" .
"Authorization: Basic " . base64_encode($client_id) . "\r\n",
'method' => 'GET',
)
);
I'm not sure but you may need a colon showing empty password "$client_id:".
Also, do a print_r($http_response_header); afterwards as it may contain information such as "Authorization Required" or something else useful.
I'm working OAuth connect Yahoo.jp login API
I try sending http request use file_get_contents but It's return errors
Here is my code
// my apps setting
$client_id = 'dj0zaiZpP~~~~~~~~~~~~~~~';
$appSecret = '129ad~~~~~~~~~~~~~~~~';
// the data to send
$data = array(
'grant_type' => 'authorization_code',
'redirect_uri' => 'My_redierct_page',
'code' => $_GET['code']
);
$data = http_build_query($data);
$header = array(
"Authorization: Basic " . base64_encode($client_id . ':' . $appSecret),
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($data)
);
// build your http request
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $data,
'timeout' => 10
)
));
// send it
$resp = file_get_contents('https://auth.login.yahoo.co.jp/yconnect/v1/token', false, $context);
$json = json_decode($resp);
echo($json->token_type . " " . $json->access_token);
The result...
file_get_contents(https://auth.login.yahoo.co.jp/yconnect/v1/token): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /var/www/html/api/auth_proc2.php on line 33
Here is another error message get using set_error_handler()
file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded
I can't understand this situation
Because I send Content-type in http header
and allow_url_fopen = on in my php.ini
Please help me~! Thanks.
The other thing I'd suggest using is CURL rather then file_get_contents for multiple reasons; first you'll have a lot more control over the request, second its more standard to use curl requests when dealing with API's, and third you'll be able to see better what your problem is.
Try replacing your code with the following and see what you get.
$client_id = 'dj0zaiZpP~~~~~~~~~~~~~~~';
$appSecret = '129ad~~~~~~~~~~~~~~~~';
$data = array(
'grant_type' => 'authorization_code',
'redirect_uri' => 'My_redierct_page',
'code' => $_GET['code']
);
$curl = curl_init('https://auth.login.yahoo.co.jp/yconnect/v1/token');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_USERPWD, $client_id . ':' . $appSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
print_r($response);
echo '<br /><br />';
print_r($info);
curl_close($curl);
I assume its probably because your using Content-Type and not Content-type and Content-Length instead of Content-length.
I'm trying for days to upload an image through PHP and OAuth2 to App.net.
Below is the PHP I'm using - it results in this error:
"error_message":"Bad Request: 'type': Required."
<?php
function sendPost()
{
$postData = array(
'type' => 'com.example.upload',
);
$ch = curl_init('https://alpha-api.app.net/stream/0/files');
$headers = array('Authorization: Bearer '.'0123456789',
'Content-Disposition: form-data; name="content"; filename="http://www.example.com/pics/test.jpg";type=image/jpeg',
'Content-Type: image/jpeg',
);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postData
));
$response = curl_exec($ch);
}
sendPost();
?>
This is their cURL example from the API documentation:
curl -k -H 'Authorization: BEARER ...' https://alpha-api.app.net/stream/0/files -X POST -F 'type=com.example.test' -F "content=#filename.png;type=image/png" -F "derived_key1=#derived_file1.png;type=image/png" -F "derived_key2=#derived_file2.png;type=image/png;filename=overridden.png"
What type is required and what do I need to change to make it work?
Any feedback is really appreciated. Thank you.
You need to do these following changes
$headers = array(
'Authorization: Bearer '.'0123456789'
);
$postData = array('type' => 'com.example.upload', 'content' => '#/roor/test.png');
Also use this as you are using https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);