I'm trying to use pure PHP to call the Azure DevOps API REST to create a release pipeline. The json required for the body is working with POSTMAN but PHP returns this error:
Array ( [$id] => 1 [innerException] => [message] => VS402903: The specified value is not convertible to type ReleaseStartMetadata. Make sure it is convertible to type ReleaseStartMetadata and try again. [typeName] => Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException, Microsoft.VisualStudio.Services.ReleaseManagement2.Data [typeKey] => InvalidRequestException [errorCode] => 0 [eventId] => 3000 )
It does not make any sense, but I think there is something regarding the return of the information instead of the information sent through the body.
Here's my code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$pat='hidden';
$url = 'https://vsrm.dev.azure.com/org-id/workspace-name/_apis/release/releases?api-version=6.0';
$body = '{
"definitionId": 1,
"description": "test",
"name": "test",
"isDraft": false,
"reason": "manual"
}';
$data_json = json_encode($body);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8; api-version=6.0','Authorization: Basic '.$pat));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
print_r ($data);
curl_close($ch);
?>
I found the answer, the error is because the json that I was sending through the body has some escaping characters \n\ etc.
With this, I have cleaned it up, and put it below the $data_json = json_encode($body);
$body_formatted=rtrim(ltrim(str_replace('\\', '', str_replace('\n', '', $data_json)), '"'), '"');
Use body_formatted on the post option curl_setopt($ch, CURLOPT_POSTFIELDS,$body_formatted);
Hope it's helps for anyone.
Related
I want to send json data using cURL in php, but the problem is that cURL is not posting any data.
NOTICE: cURL is properly installed and configured.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, array($jsonDataEncoded));
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_exec($ch);
The json Data is working fine but the cURL post is not posting anything and also not giving any type of warnings/notice or error.
as far as i can see, you do 3 mistakes
1: don't do curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");, the correct way to tell curl that you want a POST request is curl_setopt($ch, CURLOPT_POST, true);
2: when you give CURLOPT_POSTFIELDS an array, its actually converted to a multipart/form-data encoding, which is not what you want (you want to transfer a json)
3: your $sender and $message_to_reply seem to be just inserted in to the json raw. what happens if your $message_to_reply contains an " or ' ? it will invalidate the json. consider encoding it properly, for example using json_encode, like
$jsonData = array (
'recipient' => array (
'id' => $sender
),
'message' => array (
'text' => $messaage_to_reply
)
);
$jsonDataEncoded = json_encode ( $jsonData, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
but, provided that $sender and $message_to_reply is already properly json encoded, the only reason your original code doesn't work, as far as i can see, is that you give CURLOPT_POSTFIELDS an array, thus, all that's needed to fix it would be to remove "array" from that line, like curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonDataEncoded);
Try this;
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(json_decode($jsonDataEncoded)));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
You probably don't want to pass all data to one key.
Output of print_r(array($jsonDataEncoded))
Array ( [0] => { "recipient":{ "id":"me" }, "message":{ "text":"hello" } } )
Output of print_r(json_decode(array($jsonDataEncoded)))
Array ( [0] => stdClass Object ( [recipient] => stdClass Object ( [id] => me ) [message] => stdClass Object ( [text] => hello ) ) )
Well after all the try, Here is the answer:
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
$jsonDataEncoded = $jsonData;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Here i removed the array//
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// By default in PHP7 CURL_SSL_VERIFYPEER, is true. You have to make it false//
$result = curl_exec($ch);
After executing the PHP Script, I am getting the following error – Any help is appreciated. Based on my understanding, I created an array based on the bugzilla documentation - Thanks in advance
https://bugzilla.readthedocs.io/en/5.0/api/core/v1/bug.html#create-bug
{"code":32000,"error":true,"message":"Could not parse the 'params' argument as valid JSON. Error: malformed number (no digits after initial minus), at character offset 1
$url ="http://localhost:8080/bugzilla/rest/bug";
$data = array(
"product" => "TestProduct",
"component" => "TestComponent",
"version" => "unspecified",
"summary" => "'This is a test bug - please disregard",
"alias" => "SomeAlias",
"op_sys" => "All",
"priority" => "P1",
"rep_platform" => "All"
);
$str_data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-Type: application/json", "Accept: application/json"));
$username = 'ashish.sureka#in.abb.com';
$password = 'incrc';
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
$result = curl_exec($ch);
curl_close($ch);
echo $result
You have this:
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
which sends your array of data as a conventional key=value form submission, when you should have
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
^^^^^
which would send your JSON-encoded array instead.
You send $data in CURLOPT_POSTFIELDS but I think you need to give it $str_data which is encode in JSON
I think you have to replace
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
with
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
to transfer the json encoded array instead of the raw php array.
I need to do this command
root#debian:~# curl -X PUT -d '{ "date": "2.5.", "order": 2, "prize": 45 }' '[URL]'
in PHP (or Python). But I have no idea how to do it. I tried this:
$data = '{ "date": "2.5.", "order": 2, "prize": 45 }';
$data = json_encode($data);
echo $data;
$ch = curl_init([URL]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
But this returns:
{ "error" : "Error: No data supplied." }
Any idea how to reproduce it in PHP/Python?
$url = "[URL]";
$data = array(
"date" => "2.5.",
"order" => "2",
"prize" => 45
);
$json_data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
subprocess.call or subprocess.run will do what you need for this, although the output will get dumped to stdout, so you'll also need to redirect it if you want to manipulate the returned data. However, you could also use requests, like some other commenters have suggested.
https://docs.python.org/3.5/library/subprocess.html
import subprocess
import tempfile
with tempfile.TemporaryFile() as tmp:
subprocess.call(["curl", "-X", "PUT", "-d", '{ "date": "2.5.", "order": 2, "prize": 45 }', '[URL]'], stdout=tmp)
tmp.seek(0)
data = tmp.read()
Accoridng to the PHP docs,
http://php.net/manual/en/function.http-build-query.php
http_build_query accepts an array or object as the paramater.
Also, json_encode returns a string:
http://php.net/manual/en/function.json-encode.php
So, you need to change the way you are using them.
Further, using http_build_query might be preferable since it url-encodes the given params:
When POSTing an associative array with cURL, do I need to urlencode the contents first?
So you need to pass an array to the http_build_query function to make it work:
Example (from above link):
$curl_parameters = array(
'param1' => $param1,
'param2' => $param2
);
$curl_options = array(
CURLOPT_URL => "http://localhost/service",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $curl_parameters ),
CURLOPT_HTTP_VERSION => 1.0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
curl_close( $curl );
Good evening, I have an account on Todoist. I would use the Todoist API to get all the projects. I wrote the following code:
$url = "https://todoist.com/API/v6/sync";
$post_data = array(
'token' => "12345678901234567890abcdefabcdef01234567",
'seq_no' => "0",
'resource_types' => '["projects"]'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
print_r($output);
curl_close($ch);
The output is a string like this:
{"TempIdMapping":{},"seq_no_global":6201059540,"seq_no":6201059540,"UserId":7179424,"Projects":[{"user_id":7179424,"name":"Project1","color":1,"is_deleted":0,"collapsed":0,"id":165361294,"archived_date":null,"item_order":1,"indent":1,"archived_timestamp":0,"shared":false,"is_archived":0},{"indent":1,"name":"Inbox","user_id":7179424,"color":7,"is_deleted":0,"collapsed":0,"inbox_project":true,"archived_date":null,"item_order":0,"is_archived":0,"archived_timestamp":0,"shared":false,"id":165339673}]}
Is there a way to convert this output into an array?
Example:
TempIdMapping => {},
seq_no_global => 6201059540,
seq_no => 6201059540
and so on...
Your output is JSON formated, so you can use json_decode like so
json_decode($output, true);
The second parameter convert the result to an associative array instead of an stdObject
I'm trying to send out an outbound call with the callfire REST API and am having some difficulty doing so. Here's my code (adapted from https://developers.callfire.com/docs.html#createVoiceBroadcast):
<?php
$username = '...';
$password = '...';
$data = array(
'name' => 'Automation Test',
'fromNumber' => '...',
'recipients' => array(
array('phoneNumber' => '...')
),
'answeringMachineConfig' => 'AM_AND_ALIVE',
'liveSoundText' => 'hello, world!',
'machineSoundText' => 'hello, world!'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://api.callfire.com/v2/campaigns/voice-broadcasts');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = json_decode(curl_exec($ch));
print_r($result);
The problem is in the response. It's as follows:
stdClass Object
(
[httpStatusCode] => 415
[internalCode] => 0
[message] => Exception in API
)
The 415 status code is for "Unsupported Media Type" per https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error but since I'm not uploading any media that error doesn't really make a lot of sense.
Maybe my value for answeringMachineConfig is invalid. idk what AM_AND_LIVE is supposed to mean but it's in the example so I'm using it. If there's only a small number of possible values the documentation should say so..
You need to set content type to 'application/json'.
Old I know, but just ran across it. Perhaps:
'answeringMachineConfig' => 'AM_AND_ALIVE',
should be:
'answeringMachineConfig' => 'AM_AND_LIVE',
You wrote ALIVE instead of LIVE