POST request with JSON body - php

I would like to add a post to a Blogger blog via PHP.
Google provided the example below. How to use that with PHP?
You can add a post for a blog by sending a POST request to the post
collection URI with a post JSON body:
POST https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json
{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}

You need to use the cURL library to send this request.
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Close the cURL handler
curl_close($ch);
// Print the date from the response
echo $responseData['published'];
If, for some reason, you can't/don't want to use cURL, you can do this:
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
// http://www.php.net/manual/en/context.http.php
'method' => 'POST',
'header' => "Authorization: {$authToken}\r\n".
"Content-Type: application/json\r\n",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];

I think cURL would be a good solution. This is not tested, but you can try something like this:
$body = '{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);

If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...

I made API sending data via form on website to prosperworks based on #Rocket Hazmat, #dbau and #maraca code.
I hope, it will help somebody:
<?php
if(isset($_POST['submit'])) {
//form's fields name:
$name = $_POST['nameField'];
$email = $_POST['emailField'];
//API url:
$url = 'https://api.prosperworks.com/developer_api/v1/leads';
//JSON data(not exact, but will be compiled to JSON) file:
//add as many data as you need (according to prosperworks doc):
$data = array(
'name' => $name,
'email' => array('email' => $email)
);
//sending request (according to prosperworks documentation):
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
"X-PW-Application:developer_api\r\n".
"X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
//engine:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
//compiling to JSON (as wrote above):
$resultData = json_decode($result, TRUE);
//display what was sent:
echo '<h2>Sent: </h2>';
echo $resultData['published'];
//dump var:
var_dump($result);
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<h1><?php echo $msg; ?></h1>
Name: <input type="text" name="nameField"/>
<br>
Email: <input type="text" name="emailField"/>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>

<?php
// Example API call
$data = array(array (
"REGION" => "MUMBAI",
"LOCATION" => "NA",
"STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data);
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string) ,
'API-TOKEN-KEY:'.$authToken )); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);

Related

Could not send nested multi dimensional json object POST request in PHP [duplicate]

I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

Is there a way to get OAuth 2.0 token directly with CURL?

I want to get an access token to call to Google Directory API. I have seen several posts with PHP Curl code, but everytime there has to be a human action to permit access before you get the access token. Is there a way to make a CURL request and get the access token directly?
This is my code so far:
define("CALLBACK_URL", "http://localhost/los/index");
define("AUTH_URL", "https://accounts.google.com/o/oauth2/auth");
define("ACCESS_TOKEN_URL", "https://oauth2.googleapis.com/token");
define("CLIENT_ID", "**.apps.googleusercontent.com");
define("CLIENT_SECRET", "**");
define("SCOPE", "https://www.googleapis.com/auth/admin.directory.device.chromeos");
function getToken(){
$curl = curl_init();
$params = array(
CURLOPT_URL =>
ACCESS_TOKEN_URL."?"."&grant_type=authorization_code"."&client_id=".
CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=". CALLBACK_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_NOBODY => false,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-Length: 0",
"content-type: application/x-www-form-urlencoded",
"accept: *",
"accept-encoding: gzip, deflate",
),
);
curl_setopt_array($curl, $params);
$response = curl_exec($curl);
$err = curl_error($curl);
echo $response;
curl_close($curl);
if ($err) {
echo "cURL Error #01: " . $err;
} else {
$response = json_decode($response, true);
if(array_key_exists("access_token", $response)) return $response;
if(array_key_exists("error", $response)) echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
}
When I run it I get this error message:
{ "error": "invalid_request", "error_description": "Missing required parameter: code" }Missing required parameter: codec
I've just been through a similar problem with using PHP cURL to get an access token from the http code returned by the Google API after the user authorizes the consent screen. Here's my long-winded answer:
From least to most important: you should start by fixing the brackets after your if conditions:
if (array_key_exists("access_token", $response)) {
return $response
} elseif (array_key_exists("error", $response)) {
echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
The error message "Missing required parameter: code" appears because you need to post the code that was returned in the url after the client authorizes your app. You'd do that by doing something like:
CURLOPT_URL => ACCESS_TOKEN_URL."?"."&code=".$_GET['code']."&grant_type=authorization_code"."&client_id=".CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=".CALLBACK_URL,
To make it more semantic you'd define the $authorization code variable before that:
$authorizationCode = $_GET['code'];
Lastly, the most important part is that to get an Access Token from Google you need to used the cURL post method as shown in the documentation:
https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code
You can do that with PHP cURL with this command:
curl_setopt( $ch, CURLOPT_POST, 1);
But then you need to break your URL into two parts: the host and the fields to be posted. To make it easier to read, you can setup your endpoint and the fields into variables:
$endpoint = 'https://oauth2.googleapis.com/token';
$fieldsToPost = array(
// params for the endpoint
'code' => $authorizationCode, //being that $authorizationCode = $_GET['code'];
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => CALLBACK_URL,
'grant_type' => 'authorization_code',
);
Then you can use the $enpoint to set the url and http_build_query() to set up your fields. In the end, adapting your code to the code that worked for me would look something like this:
function getToken() {
$endpoint = 'https://oauth2.googleapis.com/token';
$fieldsToPost = array(
// params for the endpoint
'code' => $authorizationCode, //being that $authorizationCode = $_GET['code'];
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => CALLBACK_URL,
'grant_type' => 'authorization_code',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $endpoint);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fieldsToPost));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
// get curl response, json decode it, and close curl
$googleResponse = curl_exec($curl);
$curl_error = curl_errno($curl);
$googleResponse = json_decode( $googleResponse, TRUE );
curl_close( $curl );
return array( // return response data
'url' => $endpoint . '?' . http_build_query( $params ),
'endpoint' => $endpoint,
'params' => $params,
'has_errors' => isset( $googleResponse['error'] ) ? TRUE : FALSE, // b oolean for if an error occured
'error_message' => isset( $googleResponse['error'] ) ? $googleResponse['error']['message'] : '', // error message
'curl_error' => $curl_error, //curl_errno result
'google_response' => $googleResponse // actual response from the call
);
}
To check the response you can use the following print function to see the response:
if (isset($_GET['code'])) {
$response = getToken();
echo '<pre>';
print_r($response);
die();
}
I know it's been a long time and you've probably found a workaround but I hope this is still useful for future projects. Cheers!

JSON Error on posting Data using PHP

Following is the coding I have done. But after posting the data, I am getting error as:
'message' => string ''from' and 'to' date must be given' (length=34).
Following is my code:
$auth_token=$_REQUEST['auth_token'];
$ch = curl_init('https://api.datonis.io/api/v3/datonis_query/thing_aggregated_data');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'X-Auth-Token:'.$auth_token,
'thing_key:6f2159f998',
'idle_time_required:true',
'from:2016/02/02 17:05:00',
'to:2016/08/29 17:10:00',
'time_zone:Asia/Calcutta',
'Content-Type:application/json',
),
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
//var_dump($response);
$responseData = json_decode($response, TRUE);
// Print the date from the response
var_dump($responseData);
Actually I also want to get the data but the details are contained in the post request data.
use "CURLOPT_POSTFIELDS":
$data = array("from" => "2016/02/02 17:05:00", "to" => "2016/08/29 17:10:00");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')

Consuming a Jira REST API

I would like to consume a Jira REST API, but have been unsuccessful.
The Jira site gives the following request URL:
curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json" http://localhost:8090/rest/api/2/issue/
And this is the json array, which is located on a file called collector.json:
"fields": [
{
"project":
{
"key": "ATL"
},
"summary": "REST ye merry TEST.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Task"
}
}
]
}
The following is the code:
<?php
include_once "collector.php";
$jiraValues = jsonArray("collector.json");
$jira_url = "http://jira.howareyou.org:8091/rest/api/2/issue/createmeta";
$jiraString = json_encode($jiraValues);
$request = curl_init($jira_url); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($request, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($request, CURLOPT_ENCODING, "");
curl_setopt($request, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $jiraString); // use HTTP POST to send form data
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
curl_setopt($request, CURLOPT_URL, $jira_url);
$json_raw = curl_exec($request); // execute curl post and store results in $json_raw
curl_close($request); // close curl object
// This line takes the response and breaks it into an array using the specified delimiting character
$jira_response = json_decode($json_raw, TRUE);
print_r($jira_response);
When I run it, Nothing happens. I get no feedback.
I found it here, and replaced the information with my valid information.
Firstly define some helpful globals to help :
define('JIRA_URL', 'http://jira.howareyou.org:8091');
define('USERNAME', '');
define('PASSWORD', '');
Then we need to define a post method :
function post_issue($data) {
$jdata = json_encode($data);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_URL => JIRA_URL . '/rest/api/2/issue/createmeta' . $resource,
CURLOPT_USERPWD => USERNAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_RETURNTRANSFER => true
));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
Then how we want to use it is like so :
Create a new issue
$new_issue = array(
'fields' => array(
'project' => array('key' => 'TIS'),
'summary' => 'Test via REST',
'description' => 'Description of issue goes here.',
'priority' => array('name' => 'Blocker'),
'issuetype' => array('name' => 'Task'),
'labels' => array('a','b')
)
);
Call our previously made function passing in the new issue :
$result = post_issue($new_issue);
if (property_exists($result, 'errors')) {
echo "Error(s) creating issue:\n";
var_dump($result);
} else {
echo "New issue created at " . JIRA_URL ."/browse/{$result->key}\n";
}
A basic example of posting a new issue via REST
Note: The Jira API URL may need to be configured slightly

Send json post using php

I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

Categories