PHP HTTP 500 trying to make GET request from an api - php

I'm trying to do A GET request to an API but it gives me a 500 Http error.
I tried the same thing on https://reqbin.com/ and it worked without any error
What's the problem in my code?
My code:
$addr = $_GET['addr'];
$api_key = 'secure';
$url = 'https://www.blockonomics.co/api/merchant_order/'.$addr;
$options = array(
'http' => array(
'header' => "Authorization: Bearer $api_key",
)
);
$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
$object = json_decode($contents);

You can use this code to catch any error messages:
<?php
$addr = $_GET['addr'];;
$api_key = 'your_api_key';
$url = 'https://www.blockonomics.co/api/merchant_order/'.$addr;
$options = array (
'http' => array (
'header' => "Authorization: Bearer $api_key",
'ignore_errors' => true
)
);
$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
$object = json_decode($contents);
if($object->status != 200) {
echo $http_response_header[0]."\n".$contents;
}
This way you will see the error message which tells you what is wrong:
HTTP/1.1 500 Internal Server Error
{"status": 500, "message": "Order not found."}

Related

How to add Content-length To http request in php

I want to use octoparse API.
AND I have error when I want to clear data in octoparse API.
AND this my code
ini_set('max_execution_time', 300);
$url = 'https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>';
$options = array(
'http' => array(
'header' => "Authorization: bearer <mykey>",
'method' => 'POST'
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo 'error';
}
var_dump($result);
My result
Warning: file_get_contents(https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required
And I try to add Content-length But It have an error My new code:
ini_set('max_execution_time', 300);
$url = 'https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>';
$a=strlen($url);
$options = array(
'http' => array(
'header' => "Authorization: bearer <my key>",
'method' => 'POST',
'header' => sprintf('Content-Length: %d', $a)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo 'error';
}
var_dump($result);
My result
Warning: file_get_contents(https://dataapi.octoparse.com/api/task/RemoveDataByTaskId?taskId=<mytaskid>): failed to open stream: HTTP request failed!
Can anyone know how to solve my problem.
Thank.
you are using multiple headers in HTTP. if you are using multiple headers then follow this process
'header' => array(
"Authorization: bearer <my key>",
sprintf('Content-Length: %d', $a)
),
And you can also used this code
$requestHeaders = array(
'Content-type: application/x-www-form-urlencoded',
'Authorization: bearer <my key>',
sprintf('Content-Length: %d', strlen($url));
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $requestHeaders),
)
);

Error 400 with PATCH method using PHP stream_context_create function to pass JSON data to API

I am trying to post to this Microsoft API but I'm getting an Error 400. Works fine when using their browser-based API test console and in Postman but I can't get it working using my PHP code below. Where am I going wrong?
$myObj->update->name = "API test";
$myObj->update->qnaList->qnaId = "331";
$myObj->update->qnaList->answer = "I have been updated";
$myObj->update->qnaList->source = "Editorial";
$myObj->update->qnaList->questions->add = "What is your name";
$myObj->update->qnaList->metadata->add->name = "category";
$myObj->update->qnaList->metadata->add->value = "personality";
$data = json_encode($myObj);
$url = '[https://apiurl]';
$options = array(
'http' => array(
'method' => 'PATCH',
'content' => $data,
'header' => "Content-Type: application/json\r\n" .
"Ocp-Apim-Subscription-Key: [mykey]"
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
print_r($response);
There are problems with the JSON body you are trying to send.
This works for me and returns 204:
<?php
$myObj->update->name = "API test";
$myObj->update->qnaList = array();
$myObj->update->qnaList[0]->qnaId = "1";
$myObj->update->qnaList[0]->answer = "I have been updated";
$myObj->update->qnaList[0]->source = "Editorial";
$myObj->update->qnaList[0]->questions->add = array();
$myObj->update->qnaList[0]->questions->add[0] = "What is your name";
$myObj->update->qnaList[0]->metadata->add = array();
$myObj->update->qnaList[0]->metadata->add[0]->name = "category";
$myObj->update->qnaList[0]->metadata->add[0]->value = "personality";
$data = json_encode($myObj);
$kbid = "<YOUR-KB-ID>";
$url = 'https://westus.api.cognitive.microsoft.com/qnamaker/v3.0/knowledgebases/' . $kbid;
$options = array(
'http' => array(
'ignore_errors' => true,
'method' => 'PATCH',
'content' => $data,
'header' => "Content-Type: application/json\r\n" .
"Ocp-Apim-Subscription-Key: <YOUR-KEY>\r\n"
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result, true);
echo $response . "\r\n";
?>

Twitter API works only with one method

$key = 'fd2fdfsdfsdfdsf';
$secret = 'fdsfdsfdsfdsfdsfsdf';
$basic_credentials = base64_encode($key.':'.$secret);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Authorization: Basic '.$basic_credentials."\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => 'grant_type=client_credentials'
)
);
$context = stream_context_create($opts);
$pre_token = file_get_contents('https://api.twitter.com/oauth2/token', false, $context);
$token = json_decode($pre_token, true);
if (isset($token["token_type"]) && $token["token_type"] == "bearer")
{
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Authorization: Bearer '.$token["access_token"]
)
);
$context = stream_context_create($opts);
$data = file_get_contents('https://api.twitter.com/1.1/search/users.json?q=twitter', false, $context);
var_dump($data); die();
The code above returns false. I have no idea why. When I change the url into:
https://api.twitter.com/1.1/statuses/user_timeline.json?count=200&user_id=43243243
It works perfectly and returns the whole JSON.
Why is that so? I can't get it to work with any other API methods other than this one. The key and secret are the same in each situation. Nothing should be changed.

Http POST request get headers and body

I am currently using the below mentioned code to make http post request and it only returns body. I want the body and headers both. How I can I get body and headers both with file_get_content method or CURL?
$sURL = "url";
$sPD = "data";
$aHTTP = array(
'http' =>
array(
'method' => 'POST',
'header' => "Content-Type: application/atom+xml"
'content' => $sPD
)
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
Try:
$context = stream_context_create($aHTTP);
$stream = fopen($sURL, 'r', false, $context);
$contents = stream_get_contents($stream);
$metadata = stream_get_meta_data($stream);
You can also use the HTTP Functions if available.

php file_get_content returing 401 on failed

I have web app and api and my login system works with api so it retruns: header status 200 if it success(username and password are correctly) otherwise it returns HTTP/1.0 401 Unauthorized and json message e.x: {success: 0 , "wrong username/password"} (tested with POSTMEN plugin in google chrome)
For e.x if i want to make a request:
$method = "login";
$data = array("user"=>"test", "pass"=>"test");
send_re($method, $data);
this is my function send_re
function send_re($method, $data){
$url = "api.location/".$api_method;
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header'=> "Content-Type: application/x-www-form-urlencoded\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
return stripslashes( json_encode( $result) );
}
if my $data are correctly e.x username and password but if they are not I am not getting the error message but this:
A PHP Error was encountered
Severity: Warning
Message: file_get_contents(http://85.10.229.108/home/login): failed to open stream: HTTP request
HTTP/1.0 401 Unauthorized
Filename: libraries/api.php
Is there any way to escape this problem and get the message from api?
function send_re($method, $data){
$url = "api.location/".$api_method;
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header'=> "Content-Type: application/x-www-form-urlencoded\r\n",
'ignore_errors' => true
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
return stripslashes( json_encode( $result) );
}
Just add 'ignore_errors' => true and it's do the trick.
reference: http://php.net/manual/en/context.http.php

Categories