Content
PHP Post Request for API [SOLVED]
Added by Luca Black over 7 years ago
Hello,
i’m new to API world, i read the API v3 Documentation and start my adventure with Open Project API.
I fond the way for read the projects / work packages created but i’m blocked in the creation of new work packages.
Google and the forum explained me that i need to send a POST request with the API and send a JSON with the data of the project.
How can i make the POST request via PHP?
Now i have a script like that
<?php
$curl = curl_init();
$token = "my_api_key_token";
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Basic ".base64_encode('apikey:'.$token)));
// the json is copied by another example in this forum
$json = '{
"subject": "new work_package",
"description": {
"format": "textile",
"raw": "hallo"
},
"_links": {
"type": {
"href": "/api/v3/types/1",
"title": "Task"
},
"status": {
"href": "/api/v3/statuses/1"
},
"priority": {
"href": "/api/v3/priorities/8",
"title": "Normal"
},
"assignee": {
"href": "/api/v3/users/3"
}
}
}';
// SEND THE POST REQUEST TO API FOR THE CREATION
curl_close($curl);
?>
How can i do with php the “SEND POST REQUEST” ???
Thanks guys!
PS: i tried that code without result
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
Replies (1)
Sorry for the post, after some hours of tests and searches (not in API documentation but in other GENERAL API documentation i found the solution)
If someone need this is the script
<?php $proxy = 'my_proxy_url_and_port'; $token = 'my_token'; $url_api = 'http://my_url/api/v3/work_packages?notify=false'; $arrHeader = Array(); $arrHeader[] = "Authorization: Basic ".base64_encode('apikey:'.$token); $arrHeader[] = "Content-Type: application/json"; $json_file = '{ "subject": "TEST VIA API", "description": { "format": "textile", "raw": "test via API" }, "_links": { "type": { "href": "/api/v3/types/1", "title": "Task" }, "status": { "href": "/api/v3/statuses/1" }, "priority": { "href": "/api/v3/priorities/8", "title": "Normal" }, "assignee": { "href": "/api/v3/users/34" }, "project": { "href": "/api/v3/projects/36", "title": "Test via API" } } }'; $curl = curl_init(); curl_setopt($curl, CURLOPT_PROXY, $proxy); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $arrHeader); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $json_file); curl_setopt($curl, CURLOPT_URL, $url_api); $result = curl_exec($curl); if(curl_errno($curl)){ echo 'Request Error:' . curl_error($curl); } print_r($result); curl_close($curl); ?>In my example there MUST exist and USER 34 and a PROJECT 36