If I use the following:
$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
echo $homepage;
The data is displayed as follows:
{"user":{"profile":{"Id":{"Label":"User Id","Value":102210},"User":{"Label":"User Name","Value":"tom"}
I tried the following that I discovered on here in another post but the page remains blank other than User:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://www.website.com/api/v1/members/102210",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true); //because of true, it's in an array
echo 'User: '. $response['User']['User Name'];
You're misinterpreting the JSON data. There is no User key in the root of the json object and there is no User Name key inside of that either. When you visualize the JSON, this is what it looks like:
What you seem to be looking for is:
echo 'User: ' . $response['user']['profile']['User']['Value'];
I'm not sure why you'd switch to cURL if the file_get_content method works for you. You should be able to simply do this:
$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
$response = json_decode($homepage, true);
echo 'User: ' . $response['user']['profile']['User']['Value'];
Related
I am attempting to use Auth0 to secure an API on Laravel Framework 8.83.22
I am using this tutorial (machine-to-machine) https://auth0.com/blog/build-and-secure-laravel-api/
Problem:
Curl at the command line works fine:
curl -X GET -H "Authorization: Bearer ***REMOVED***" -H "Content-Type: application/json" -d "{}" http://localhost:8000/api/weightrecords/4195
However, making the call inside a PHP script times out (I've tried longer timeouts with no help). I get the token fine (SECTION 1 below) but SECTION 2 times out (cURL Error #:Operation timed out after 30000 milliseconds with 0 bytes received).
public function test_api()
{
//SECTION 1: Get the token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://**REMOVED***.auth0.com/oauth/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"client_id\":\"qDpVdykOlRYkxOdq8J7a2CJ7X7E3WUK8\",\"client_secret\":\"**REMOVED**\",\"audience\":\"**REMOVED**",\"grant_type\":\"client_credentials\"}",
CURLOPT_HTTPHEADER => array(
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$response_array = json_decode($response);
$access_token = "authorization: Bearer " . $response_array->access_token;
echo $access_token;
}
//SECTION 2: Use the token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_VERBOSE => true,
CURLOPT_URL => "http://127.0.0.1:8000/api/weightrecords/4195",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
.env
AUTH0_STRATEGY=api
AUTH0_DOMAIN=**REMOVED**.us.auth0.com
AUTH0_CLIENT_ID=qDpVdykOlRYkxOdq8J7a2CJ7X7E3WUK8
AUTH0_AUDIENCE=**REMOVED**
API_IDENTIFIER=**REMOVED**
kernal.php
protected $routeMiddleware = [
//...all the defaults...
'jwt' => \App\Http\Middleware\CheckJWT::class, //<<<<------Added
];
api.php
Route::apiResource('weightrecords', ApiController::class);
CheckJWT.php and auth.php same as in article..
What does $access_token look like?
Try using the post data without the escapes.
You may need to urlencode() the json. Typically not, but I have had it help with one API.
This is how I begin the trouble shooting process.
Add these options.
CURLOPT_CONNECTTIMEOUT=>10,
CURLOPT_FAILONERROR=>true,
CURLINFO_HEADER_OUT=>true,
Get the curl_getinfo:
$response = curl_exec($curl);
$err = curl_error($curl);
$info = var_export(curl_getinfo($curl),true);
echo $info;
You should see the out going request header in $info because of the CURLINFO_HEADER_OUT=>true.
I have a PHP script where it returns details about the request including Body, $_POST, $_GET, $_REQUEST, $_SERVER
LINK to see your request details
You can use this link as your curl URL.
I want to change the response of an API if an incorrect value is typed..
<?php
if(isset($_GET['q']))
{
$q = ($_GET['q']);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.me.co/bank/resolve?account_number=".$q."&bank_code=".$bcode."",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer demo_03a647487df8a50d343aeb66d2a7305yhfkfllba",
"Cache-Control: no-cache",
),
));
$response = curl_exec($curl);
$err =
curl_error($curl);
curl_close($curl);
}
?>
Now $response is the ouput and irrespective of wat input the user types the $response will ouptut something. If the users input is wrong, it will show a php error which will scare the user.
$q is the users input and have tried using something like
if(!$response)
{
echo "incorrect";
}
The only thing that worked was turning off the error reporting for that page which i do not want cos i dont want the user to proceed.
In summary what i want is to customise the error from $response if the user input is wrong. Thanks as usual.
I'm currently trying to get every title of my JSON decoded output in a variable
This is what works for me as curl
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://api.irail.be/disturbances/?format=json&lang=nl',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'cache-control: no-cache',
'content-type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
// Decode JSON response and get only the data needed:
$response = json_decode($response);
$response = $response->disturbance[0];
var_dump($response);
$name = $response->title;
echo $name;
When I remove the [0] behind disturbance I am getting a blank $name. Does anyone know how I can fix this?
Thank you
You can access your objects via the keys, but "disturbance" is not a key, it is a value that the key type can take.
You need first to filter your data to get only the items with type = 'disturbance', and then you can get the titles.
Here is an example :
$response = json_decode($response);
$disturbanceItems = array_filter($response, function ($item){return $item->type == 'disturbance';});
echo $disturbanceItems[0]->title ;
I use postman for the first time.
My goal is to download a JSON file.
I managed to look at the code for cURL in postman:
But if I test the code in the command line, I can not log in.
Actually, I want to call the JSON file via PHP. I have tested initial approaches. In addition to the problem that I can not authenticate myself here, I think that I need more values. For example POSTFIELDS. Is that correct and if so, how do I find what I have to enter in Postman? Here is my initial Code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.divessi.com/divessi/index.php",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "..",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic BASE64",
"Cache-Control: no-cache",
"Postman-Token: TOKEN",
"content-type: ??"
),
));
$response = curl_exec($curl);
$obj = json_decode($response);
$events = array();
if ($obj)
{
$events = $obj[0]->DATA;
}
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
} else {
foreach ($events as $event) {
...
}
I have 2 json response from 2 different urls, the first step one if user fill the customernumber with post method to get the billNo value as below:
{
"Customer":[
{
"billNo":"1001337"
}
],
}
The second one to another url user fill the billNo (got from the first step above) in a form with post method to get details result response like this:
{
"Billing":[
{
"billAccName":"John Doe",
"billAccStatus":"Active"
}
],
}
My question is it possible to combine this result with only using first step only fill up the customernumber? Within the expected result is:
{
"Billing":[
{
"billAccName":"John Doe",
"billAccStatus":"Active"
}
],
}
I am using Curl with PHP to get those responses, is there any other way to achieve this, maybe need to insert to the temp DB table first?
Edited add the script.
<form class="form-response" method="POST" action="postform.php">
<h2 class="form-response-heading">get Response</h2>
<input name="customernumber" class="form-control" type="text" autofocus="" required="" placeholder="phonenumber"customernumber">
<button class="btn btn-lg btn-primary btn-block" type="submit">Get Response</button>
</form>
<?php
$customernumber = $_POST['customernumber'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"customernumber\":\"" .$customernumber . "\"}",
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikeynumbers",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Update Script:
<?php
$phone = $_POST['customernumber'];
$curl = curl_init();
$data = array("customernumber" => $phone);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikey",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$result = json_decode($response);
$billno = $result->Customer[0]->billNo;
//now here, make your second API call using the Bill Number retrieved from the response
$billAccNo = $_POST['billNo'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/getBillingDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"billAccNo\":" .$billAccNo . "}",
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapike",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
Thanks for any suggestions
You just need to programatically retrieve the Bill No from the data returned by the first request, and then put it in a variable to be included in your second request. You can do that by decoding the JSON data into a PHP object and then extracting the correct field from it.
I've assumed that you either only ever get one Customer back from the first request, or that you only ever are interested in the first Customer record returned. If that's not the case you'll have to modify the code accordingly.
Also, you haven't provided the code used to run the second request, so I'll have to leave it to you to use the $billno variable in a suitable way in that request.
The change occurs in the else statement at the bottom of the code, where instead of just echoing the raw response we instead decode it and take the Bill No from it.
<?php
$phone = $_POST['customernumber'];
$curl = curl_init();
$data = array("customernumber" => $phone);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikeynumbers",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$result = json_decode($response);
$billno = $result->Customer[0]->billNo;
//now here, make your second API call using the Bill Number retrieved from the response
}
P.S. I also changed your input JSON data to be created reliably using json_encode. Building JSON by hand, even a simple string like this, is potentially prone to failure due to unexpected syntax errors, typos etc - instead used the tools provided to convert a PHP variable with a known-good structure into a valid JSON string in a reliable, repeatable way.