hi i wanted to make a post request to dropbox.i found there is this guzzle which can be easily send http req using php. here the http code given by dropbox
`POST /2/files/list_folder
Host: https://api.dropboxapi.com
User-Agent: api-explorer-client
Authorization: Bearer <access-token>
Content-Type: application/json
{
"path": "",
"recursive": false,
"include_media_info": true,
"include_deleted": false,
"include_has_explicit_shared_members": false
}`
This is my php code i coded for above request;
$response=$client->request('POST','https://api.dropboxapi.com',
[
'headers'=>[
'Authorization'=>'Bearer '.$API,
'User-Agen'=>'api-explorer-client',
'Content-Type'=>'application/json'
],
'form_params'=>[
'path'=>'',
'recursive'=>'false',
'include_media_info'=> 'true',
'include_deleted'=> 'false',
'include_has_explicit_shared_members'=> 'false'
]
]);
$headers = $response->getHeaders();
$body =$response->getBody();
$print=json_decode($body,true);
//Output headers and body for debugging purposes
var_dump($headers);echo"<br><br>";
var_dump($print);?>
this should give something similar to following ,but i get a small array
{"entries": [
{
".tag": "folder",
"name": "Photos",
"path_lower": "/photos",
"path_display": "/Photos",
"id": "id:bwGPfg_v6ZUAAAAAAAAAOA"
},`
what i missed here?
PS:im new to php related stuff :)
You are sending JSON, not an HTML form. So use 'json' instead of 'form_params'.
Related
There is a way to send in a firebase notidication request, various to
header:
Content-Type: application/json
Authorization: key=
Body:
{ "data":
{
"title": "Firebase notification",
"detail": "I am firebase notification. you can customise me. enjoy"
},
"to" : "c_ejgKg_0rY:APA91bEtp77PP99UuDvza1gKOKAmfqVg3ZHflWYQUGPQJFCvWy3Ortswv45MjtT8LQaRoebLqSXPTeaO21hm7QVnG694GgVmALbK5LIDAsyohKlTFlQSlwcdYQmPS5GnLGjLwfA3b34z",
"sound":"default"
}
here an example of the request, please help me, thank you
Use registration_ids instead...
Firebase Cloud Messaging HTTP protocol | Firebase
header:
Content-Type: application/json
Authorization: key =
Body:
{
"data":
{
"title": "Firebase notification",
"detail": "I am firebase notification. you can customise me. enjoy"
},
"registration_ids" : [
"c_ejgKg_0rY:APA91bEtp77PP99UuDvza1gKOKAmfqVg3ZHflWYQUGPQJFCvWy3Ortswv45MjtT8LQaRoebLqSXPTeaO21hm7QVnG694GgVmALbK5LIDAsyohKlTFlQSlwcdYQmPS5GnLGjLwfA3b34z"
],
"sound":"default"
}
I am have set up a proxy that allows me to retrieve data user side from a api only accessible server side. I have several endpoints setup and they all work just fine, but now i'm at a point where I need to send data back to the api to make a reservation. I need to
retrieve data from ajax request in proxy
send data in proxy to api
return success/error message from api to ajax request
I not sure how to do this. Here is my ajax request:
var settings2 = {
"async": true,
"crossDomain": true,
"url": "http://url?method=hello&format=json&entity=" + id,
"dataType": "json",
"data": data,
"method": "POST"
};
var a2 = $.ajax(settings2);
$.when(a2).done(function(d2) {
rp = d2;
console.log(JSON.stringify(rp));
});
and the php function and method I use for the other endpoints that only need to retrieve data from the api, it works for this:
function LocationReserve(data) {
header('Content-Type: application/json');
$url = 'api_url' . $_GET['entity'] ;
$auth = 'Authorization: key';
$ch = curl_init($url);
$options = array(
CURLOPT_HTTPHEADER => array(
$auth
),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION, 1
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Method A: Say Hello to the API
if( strcasecmp($_GET['method'],'hello') == 0){
$response['code'] = 1;
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
$response['data'] = wssLocationReserve();
}
// --- Step 4: Deliver Response
// Return Response to browser
deliver_response($_GET['format'], $response);
with this as it is I get a response back
{"code":1,"status":200,"data":"{\"Message\":\"The requested resource does not support http method 'GET'.\"}"}
I added CURLOPT_POST => true to my options and now the response is
{"code":1,"status":200,"data":"<html><head><title>411 Invalid Request</title></head><body>Invalid Request: ??</body>\r\n"}
How can I modify this to accept the data from my ajax call, send it to the api_url, and send back the response?
**EDIT example expected data by api:
{
"ReservationDay": "05/15/2015",
"Units": [{
"UnitID": 12345,
"InsuranceID": 123 (or null)
}],
"PaymentInfo": {
"FirstName": "User",
"LastName": "Userson",
"Address1": "2727 N Central Ave",
"Address2": "",
"City": "Phoenix",
"State": "AZ",
"Zip": "85022",
"Phone": "602-2877878",
"Email": "email#example.com",
"CreditCard": "6011000000000000",
"ExpirationMMYY": "1215",
"CSC": "100"
}
}
"HTTP Status Code 411 (Length Required) is sent by the server as a response when it refuses to accept a message without a content-length header, for whatever reason."
1.- Test a request sending possible missing arguments.
2.- Have you the format in which the data must be send to the second endpoint? Check the specifications of the expected data and fix your second request.
Request header
Content-Type: application/json
Authorization: Bearer [access token]
Accept: application/json
if send unicode string with message, please set Content-Type charset to UTF-8
Following is a sample request of send service.
URL-https://example.com/requests
Method - POST
Body
{
"outboundSMSMessageRequest": {
"address": [
"tel:+94771234567"
],
"senderAddress": "tel:12345678",
"outboundSMSTextMessage": {
"message": "Test Message"
},
"clientCorrelator": "123456",
"receiptRequest": {
"notifyURL": "http://128.199.174.220:1080/sms/report",
"callbackData": "some-data-useful-to-the-requester"
},
"senderName": "ACME Inc."
}
}
How to post and get responce
ajax
headers: {
'X-HTTP-Method-Override': 'POST',
'Content-Type': 'application/json'
},
or vanilla js
How to create javascript POST request to server with Headers and Data
I have found a couple of helpful links on stackoverflow but they haven't helped me complete my task because I am a complete beginner in trying to write PHP or use curl etc.
Send json post using php
Posting JSON data to API using CURL
I have been using Postman in Chrome to test API calls but I now want to put together a demo system on my Apache web server.
Does anyone have an example of a PHP webform posting to a json Object to a REST API?
Here is an example of what I want to send:
<?php
$url = "https://api.url/api/v1//accounts/create";
$jdata = json_encode($data);
$data = [{
"status": "active",
"username": ["uname"],
"password": ["pword"],
"attributes": {
"forenames": ["fname"],
"surname": ["lname"],
"emailAddress": ["email"]
},
}]
?>
Any advice would be fantastic. Like I said, I am new to curl and php, am unfamiliar with the array approach mentioned in the other articles and the ["info"] elements should be populated with the information filled in on my webform.
I hope I have been concise and explanitory but please let me know if you need anymore information.
Snook
Try something like the following, modifying steps 1 and 2 accordingly:
function sendRequest($data,$url)
{
$postdata = http_build_query(array('data'=>$data));
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded \r\n",
//"X-Requested-With: XMLHttpRequest \r\n".
//"curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)\r\n",
'content' => $postdata,
'ignore_errors' => true,
'timeout' => 10,
)
);
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);
}
// 1.- add your json
$data = '[{
"status" : "active",
"username" : ["uname"],
"password" : ["pword"],
"attributes" : {
"forenames" : ["fname"],
"surname" : ["lname"],
"emailAddress": ["email"]
},
}]';
// 2.- add api endpoint
$url= "https://api.url/api/v1//accounts/create";
// 3.- fire
$result = sendRequest($data,$url);
// 4.- dump result
echo $result;
die();
Good luck!!
I cant retrieve json post data using fiddler
POST http://localhost/backend/login HTTP/1.1
User-Agent: Fiddler
Host: 192.168.0.147
content-type: application/json
Content-Length: 278
{
'name': 'Phill Sparks',
'location': 'England',
'skills': [
'PHP',
'MySQL',
'Laravel'
],
'jobs': [
{
'org': 'Laravel',
'role': 'Quality Team',
'since': 2012
}
]
}
routes:
Route::post('backend/login', 'UserController#backendLogin');
controller:
public function backendLogin()
{
//Input::all() and Input::json()->all() are empty
}
anything missing here?
You need to replace you single quotes ('England') with double quotes ("England") to have a valid JSON payload. You need to do this for both the keys and the values.