0

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 :)

Sophie
  • 190
  • 1
  • 9

1 Answers1

0

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.

emix
  • 14,448
  • 10
  • 62
  • 82