How to use API V2 Moz HTTP Request - php

I am trying to connect to Moz API V2, using HTTP Request by file get contents function but I am new using this... could you guys help me?
Example HTPP Request in their doc:
POST /v2/url_metrics
Host: lsapi.seomoz.com
Content-Length: [length of request payload in bytes]
User-Agent: [user agent string]
Authorization: Basic [credentials]
{
"targets": ["facebook.com"]
}
Here's the code I am trying:
$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$domains = json_encode(['targets' => 'moz.com']);
$opts = ['http' =>
[
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n'.
("Authorization: Basic " . base64_encode("mozscape-XXXXX:XXXXX")),
'content-length' => strlen($domains),
'user-agent' => $_SERVER['HTTP_USER_AGENT'],
'content' => $domains,
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);
Here is the link of documentation : https://moz.com/help/links-api/making-calls/url-metrics
I got nothing when I print result, Probably I am missing some parameter... :(
Thank you for your time :)

Most probably you're simply making an invalid request. You declare the content type as application/x-www-form-urlencoded yet sending the data as application/json.
You also need basic error handling (eg. in case of invalid credentials).
I'd write it this way:
$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$content = json_encode(['targets' => 'moz.com']);
$opts = ['http' => [
'method' => 'POST',
'content' => $content,
'header' => implode("\r\n", [
'Authorization: Basic ' . base64_encode("mozscape-XXXXX:XXXXX"),
'Content-Type: application/json',
'Content-Length: ' . strlen($content),
'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'],
]),
]];
$stream = fopen($url, 'r', false, stream_context_create($opts));
if (!is_resource($stream)) {
die('The call failed');
}
// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));
// actual data
var_dump(stream_get_contents($stream));
// free resources
fclose($stream);
To be honest, the sockets & fopen is pretty low level. It would be better for you to use an abstraction layer instead: like Guzzle.

Sorry for late solution I forgot to post here before...
Maybe someone is looking for how to use moz API V2 with PHP...
$username='Access ID';
$password='Secret Key';
$URL='https://lsapi.seomoz.com/v2/url_metrics';
$payload = json_encode(array("targets" => ["moz.com"]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_close ($ch);
print_r(json_decode($result, true));

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.

POST Request in PHP is not returning anything

I am trying to use Thycotic PAM API. According to their documentation, The following is a sample HTTP POST request. The placeholders shown need to be replaced with actual values.
POST /SecretServer/webservices/SSWebservice.asmx/GetUser HTTP/1.1
Host: 192.168.3.242
Content-Type: application/x-www-form-urlencoded
Content-Length: length
token=string&userId=string
I can get token string and user ID from the app. With this data, following is the PHP code I am trying
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser';
$data = array(
'token' => 'token_string',
'userId' => 8
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents($url, false, $context));
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
I also tried this way:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser?token=token_string&userId=8 HTTP/1.1';
$json = json_decode(curl_get_contents($url));
var_dump($json);
Both of them are returning nothing. Any suggestion is much appreciated.
curl_setopt($ch ,CURLOPT_POST, 1);
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch ,CURLOPT_POSTFIELDS, "token=string&userId=string");
you must use this parameters

Why does stream_context_create successfully return data but not my Curl?

When I first started, I thought Curl would be an excellent way of retrieving a chunk of data in the format json. It didn't work. I tried doing some Ajax request instead, but that didn't work either.
Now, this is my Curl request:
$ch = curl_init("url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept' => 'application/json',
'Auth' => 'code',
));
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
... The CURL requests RETURNS a EMPTY STRING. No errors...
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: application/json\r\n" . "Auth: code",
)
);
$context = stream_context_create($opts);
$url = "";
$fp = fopen($url, 'r', false, $context);
$r = #stream_get_contents($fp);
fclose($fp);
print_r($r);
Provides a nice array with json data. Why? Isn't this literally supposed to do the same thing?
Because CURLOPT_HTTPHEADER doesn't take associated arrays. You need to add the complete header.
$ch = curl_init("url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Auth: code',
));
$data = curl_exec($ch);
curl_close($ch);
print_r($data);

file_get_contents not working for fetching data from facebook using batch requests

file_get_contents not working for fetching fata from facebook using batch requests.Am using the code below:
$url='https://graph.facebook.com/?batch=[{ "method": "POST", "relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]& access_token=xxxxxxx&method=post';
echo $post = file_get_contents($url,true);
it produces
Warning: file_get_contents(graph.facebook.com/?batch=[{ "method": "POST", "relative_url": "method/fql.query?query=SELECT+first_name+from+user+where+uid=12345"}]&access_to‌ ​ken=xxxx&method=post): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/user/workspace/fslo/test.php on line 9
I would say the most likely answer to this is that you need to pass the URL values through urlencode() - particularly the JSON string.
Also, you should be POSTing the data.
Try this code:
NB: I presume you are building the URL from several variables. If you edit the question with your actual code, I will provide a solution using that code
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_to‌ken' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
. "Content-Length: ".strlen($requestBody)."\r\n"
. "Connection: close\r\n",
'content' => $requestBody
)
);
$context = stream_context_create($opts);
$result = file_get_contents($baseURL, FALSE, $context);
A "more standard" way to do this these days is with cURL:
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_to‌ken' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseURL);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($requestBody),
'Connection: close'
));
$post = curl_exec($ch);

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