Upcoming LunaMetrics Events
San Francisco, Apr 28-30 Los Angeles, May 12-16 New York City, May 19-23 Chicago, Jun 16-18

Mozscape API Application Tutorial

Behind SEOmoz’s popular Open Site Explorer is a breadth of metric-defining data. The engineers at SEOmoz have coalesced and interpreted this data, forming well known metrics, like Page Authority and Domain Authority, and delivering meaningful counts, like External Followed Links. As SEOs, we use these metrics almost daily, accessing them via OSE, the SEOmoz toolbar, and third party applications (like HubSpot).

mozscape api

In this tutorial, we’ll examine the practice of accessing SEOmoz metrics via your own applications (like our Luna Link Rover), making use of the free version of the Mozscape API and the provided PHP Signed Authentication Example. Prior programming experience isn’t a must, but it certainly won’t hurt. All you’ll need to complete this tutorial is an SEOmoz account, a text editor (we use Sublime Text 2 in this tutorial), and a web server (for testing your application). If you don’t have access to a hosting account, you can setup a local web server using XAMPP (Windows) or MAMP (Mac).

This step-by-step walkthrough will help you understand the intricacies of our example application. We encourage you to download the completed PHP file and reference it as you read through each step. Let’s do this.

1. Generate your API credentials

In order to access the Mozscape API, you’ll need to generate a unique set of API credentials. Don’t fret; this is pretty simple. First, sign into your SEOmoz account (or, if you don’t have one, create one) and navigate to the ‘Get Started with the Mozscape API’ page. Follow the steps to generate your unique Secret Key. Once you’ve done this, you should see a nice green box with both your API Access ID and new Secret Key. Keep this tab open, as you’ll be using your credentials shortly.

2. Copy the PHP Signed Authentication Example to your text editor

Provided with the Mozscape API documentation are a number of code examples. As we’ll be using PHP to build our simple application, we’ll make use of the PHP Signed Authentication Example. Using this code as a starting point will make understanding our API calls a more feasible task.

php signed authentication example

Select all of the code provided in the Signed Authentication Example and copy it to your clipboard. Open a new file in your text editor and paste in the code. Save the file as ‘example-app.php’. It’s time to start constructing your API calls!

3. Get started with your PHP file

Since the example code omits the opening tag for PHP, we’ll start by adding it to our file. Above the first example line, include the opening tag:

php example

Note that the characters ‘//‘ denote a single line comment in PHP. In the screenshots we provide throughout this tutorial, instruction comments are preceded by an asterisk (*) — like ‘// * Add opening tag‘ above. Speaking of comments, you can learn quite a bit from the comments that SEOmoz has provided in their example code. Now is a good time to peruse these comments and get a feel for what the code does.

After you’ve had a chance to look over the code, return to the top of your file. Remember the API credentials you generated just a bit ago? It’s time to put these to use. We’re provided with a variable for each of our credentials, $accessID and $secretKey. (PHP variables always begin with the dollar sign.) Copy and paste your credentials in place of the respective sample text (i.e., ACCESS_ID_HERE). Be sure to preserve the quotation marks surrounding the variable values.

assign api credentials

Once you’ve entered your credentials, you have yourself a PHP file that, when uploaded to your web server and requested, will make a Mozscape API call. However, the format of the information returned won’t be particularly useful, and, furthermore, you’ll have to edit the file itself every time you want information about a different URL. Not to mention, you might want to specify which URL metrics your application should fetch, rather than retrieving just those defined in the example code (URL, Page Authority and Domain Authority).

4. Define URL metrics to be requested

In this tutorial, we’ll be making use of the URL Metrics API (given that our example code does the same). In the API documentation for URL Metrics, we see that, “by default, the response to a URL Metrics call includes all response fields available to your account, except Domain and Page Authority, which need to be explicitly requested.” Since we know that both Domain and Page Authority are being requested (as our example request is constructed), we can infer that some facet of our code is responsible for the explicit requests.

define url metrics requested

In fact, the $cols variable in the screenshot above does just that — its value determines which URL metrics are requested and returned. By summing the Bit Flags of metrics available in the free URL Metrics API and assigning this sum to the $cols variable, we can specify which metrics we’d like to request. You can read more about Bit Flags in the documentation linked above. Bit Flags and Response Fields (we’ll get to this) for specific URL Metrics are specified in that documentation, as well.

url metrics

Above, in the second column, we see the Bit Flag values for the Page and Domain Authority URL metrics. When we sum these values (34359738368 + 68719476736), we get 103079215104. After adding the URL Bit Flag (4), we have 103079215108. If you look at the screenshot with the $cols variable, you’ll notice that $cols‘ value is exactly that. So, as our code stands, we’re requesting the URL itself, Page Authority, and Domain Authority. Pretty cool, right?

external links

Let’s add another metric to our call: External Links. In the Bit Flag column of the External Links row, shown in the screenshot above, we see a value of 32. We add this 32 to our current total (103079215108) to get 103079215140. In your code, insert this new value in place of the old $cols value.

insert new total

If you’re working on a local web server, you can refresh the file in your browser to see the additional metric returned. Still no formatting, though. First, we have to make the information returned easy to use within our application.

5. Organize the metrics returned

Rather than printing the requested URL metrics in their ugly return format, we want to use them in a way that makes sense to our application’s users. The first step in this process is to assign each returned metric to its own unique variable. This way, metrics are easily accessible within our code.

outputting requested information

If you scroll down to the bottom of your PHP file, you’ll see that the print_r() function is being used to output the requested information. While print_r() is useful for displaying the URL metrics in the browser, it isn’t particularly helpful when it comes to segmenting the individual metrics. For this, we’ll make use of the json_decode() function — a function that, given a JSON encoded string (which the Mozscape API does indeed return), will convert that string into a PHP variable. In the case of our example, a PHP array. You can think of an array as an organized list of values (i.e., our requested URL metrics). We won’t go into too much detail about these functions, but if you care to, you can read more on json_decode() and PHP arrays.

using json_decode

For now, supplant the print_r($content); line with the $json_a = json_decode($content); line shown in the screenshot above. (Note that each line of PHP ends with a semi-colon.) Now we have an associative array that will hold the values of each of the URL metrics returned. We can assign these array values to separate variables using the keys that SEOmoz provides in the URL Metrics documentation. Keys for each metric can be found in the Response Field column of the metric table.

url metrics response fields

The keys for the metrics we’re requesting — Page Authority, Domain Authority, External Links, and URL — are upa, pda, ueid, and uu, respectively. Let’s use these keys to access our array values and store them in new variables. We can do this via the array->key syntax.

Assign Metrics to Variables

The code in the screenshot above accomplishes just what we’re looking to do, assigning URL metrics in our PHP array to their own separate variables. Notice that we’ve made use of the round() function to limit our Page and Domain Authority values to integers. (By default, they’re returned as decimal values.) The second argument in round($argument1,$argument2) (in this case, a 0) indicates to how many decimal places the function will round our values. If you’d like to get a little more granular and see numbers with, let’s say, two decimal places, you can change this argument to 2.

6. Display the URL metrics in the browser

Now that we can readily access the returned URL metrics using our newly defined variables, we want to make it easy for users to read the metrics returned. We can do this by partnering our PHP with a little HTML. We’ll be making use of the PHP echo construct and an HTML unordered list to display the URL metrics in the user’s browser. We can start our HTML structure below the PHP we’ve already written (right after the closing PHP tag).

displaying url metrics to the browser

In the screenshot above, we’ve structured our application’s HTML and created a list item for each URL metric (with the metric name bolded). We’ve used inline PHP to output the values of our URL metric variables within the appropriate list items. (Notice that the inline PHP starts and ends with the same opening and closing tags and includes the semi-colon at lines’ end.) At this juncture, you should have a functioning application that displays Mozscape metrics for the requested URL. Re-upload the PHP file to your server and/or refresh your browser to see the results thus far.

Mozscape Application Thus Far

Not too shabby, eh? We’ve come a long way. Now it’s time to make your application a bit more dynamic.

7. Accept users’ URL inputs

As it stands, our simple application works, but it isn’t incredibly useful. In the example code provided, the object URL — or the URL that we want link metrics for — is set to ‘www.seomoz.org’ (a static value). With a static object URL, we get static results. Each time we refresh our browser, we request the same link metrics for the same URL. Seems boring, doesn’t it? We want users to interact with our application, not just use it once and be on their way.

Here’s a thought: We allow users to choose the URL for which they want Mozscape link metrics. That seems a bit more useful, and it only takes a couple of steps to implement. We’ll need an HTML form to process the user’s URL input and some PHP to accept that input and set the $objectURL equal to it. Let’s start with the form.

Process Users' Input

The form itself is fairly straightforward. We’ve provided users with a URL field and a submit button so that they can request metrics for specific URLs. We’ve set the form method to ‘post’ and the action to ‘/example-app.php’, as we’ll be processing the input using the same PHP file. If you’ve uploaded your file at the root level and used the same file name, this should work properly. If not, simply set the action attribute equal to the location of the file (or the URL at which the file can be accessed on your web server).

Now, let’s move along to accepting the user’s input with PHP.

Accepting User Input

When a user submits our application’s form to the PHP file on which it resides, we want to set that input equal to our $objectURL variable (which, in the example code, is set to ‘www.seomoz.org’). To do this, we make use of the PHP $_POST variable and the name attribute we set for our URL input (‘url’). $_POST collects all of the input values submitted with our form, and ['url'] specifies which of those values we’d like to access. Just like that, we’ve accomplished our goal of allowing users to input their own URLs.

URL Metrics for Google

In the screenshot above, we’ve used our application to fetch URL metrics for Google.com. Nearly 50 million external links say that we’ve constructed a functioning test application using the Mozscape API! Woohoo!

8. Refine, expand, attribute, and launch!

Now that you have an example application up and running, the ball is in your court. Think of ways that you can augment tools like OSE by expanding upon your current application. Add some styling to make it look pretty. Read up on and comply to SEOmoz’s attribution and branding requirements. And, finally, launch your application to web users!

And so concludes our Mozscape API application tutorial. Again, if you haven’t yet, we encourage you to download the completed PHP file and play around with the code. Visit our Luna Link Rover to see a simple example of a structured web application that makes use of the Mozscape API. Also, if you happen to live in the Pittsburgh area, you should check out our upcoming Google Analytics and AdWords training. In the Google Analytics APIs class, we’ll be teaching attendees how to interact with and get the most out of the Google Analytics API.

http://www.lunametrics.com/blog/2013/01/22/mozscape-api-tutorial/

16 Responses to “Mozscape API Application Tutorial”

kimberly says:

Hi there

How to get MozRank for this code
$mozrank = $json_a->umrp;
I try this but not working
Help Plz

Travis Loncar says:

Hi Kimberly,

We do have access to MozRank with free API access. Your code looks fine there (so far as accessing the MozRank value goes).

My guess is that you forgot to add the corresponding Bit Flag (find here: http://apiwiki.moz.com/url-metrics) to the $cols value used in this tutorial. The API uses the value of the Cols query string parameter to determine which metrics it should return. Since we’re using the $cols variable to determine this value, we need to adjust it to account for MozRank.

The Bit Flag for MozRank is 16384. Adding this to our current $cols value, 103079215140, we get 103079231524. If you supplant the current $cols value with this value (103079231524), you should be able to access MozRank.

Hope this helps. Thanks for stopping by.

kimberly says:

Hi Travis,

Big Thanks

It’s working :)

Megan says:

I need multiple url checker code
Help me
Thanks

Travis Loncar says:

Hi Megan,

Check out this example of batching URLs in a single call provided by the Moz dev team. This implementation will allow you to batch 10 URLs per call to the url-metrics API (with free access).

You can read more about batching your calls here: http://apiwiki.moz.com/best-practices

If you have any trouble, feel free to comment here again. Thanks for reading.

Megan says:

hi thanks but m stuck here…
i dnt have much knowledge abt coding
like m using
print_r($contents[0]);
print_r($contents[1]);
print_r($contents[2]);
output:
stdClass Object ( [pda] => 93.7190105364 ) stdClass Object ( [pda] => 100 ) stdClass Object ( [pda] => 50.3862180601 )

hw to decode it like string

Megan says:

one more thing
with this code:echo json_encode($contents[0]);
{“pda”:93.7190105364}
now how to use this value :)

Travis Loncar says:

Megan,

You’re almost there. You see that each item in the returned array ($contents) is an Object.

You can access each object by passing $contents an index (as you’ve done in your print_r()) or by looping through the $contents array:

foreach($contents as $domain) {
echo “Domain Authority: ” . round($domain->pda, 0);
}

Notice that you access the properties of each object using the $object->property syntax. I’m rounding here so that the Domain Authority looks presentable.

You can accomplish this (unrounded) outside of a loop with the following (where 0 is the index of the $contents array):

echo $contents[0]->pda;

Hope this helps.

Megan says:

Its works :)
many thanks

Kudzai says:

Hello. I installed wamp server to follow this tutorial however when i access the file on my browser:
ie: http://localhost/php-tutorial/example-app.php,

it comes up blank. When error reporting is on, it show the followoing: ” Use of undefined constant CURLOPT_RETURNTRANSFER – assumed ‘CURLOPT_RETURNTRANSFER’ in C:\wamp\www\php-tutorial\example-app.php on line 30″

Kudzai says:

Ok i figured it out. The answer was to go to:

C:\wamp\bin\apache\apache2.4.2\bin and edit the php.ini file to uncomment (remove the ;) from the line that says “extension=php_curl.dll”.

Also had to do the same for the php.ini file under C:\wamp\bin\php\php5.4.3

Then i follow this instruction on this stackoverflow post (http://stackoverflow.com/questions/10939248/php-curl-not-working-wamp-on-windows-7-64-bit) to install the proper version of Curl for my php version (mine is php5.4.3), and i used the VC9 version:

Kudzai says:

Ok, Hello again.

I’ve reached the end of the tutorial, and everything was well, until i tried to enter google.com in my form. I get a message underneath the URL entry box saying “!Please enter a URL.” I’ve uploaded it here: http://fifaz.org/php-tutorial/example-app.php

Travis Loncar says:

Hi Kudzai,

Thanks for all of the comments; glad you were able to work out the WAMP stuff. (I would’ve had to research it, as well.)

The URL form field uses the HTML5 URL input type, thus it requires that you include the protocol (http://) in the URL. Try again with http://google.com, and it should validate just fine. Also, I’d change the form action to just example-app.php; the current path specified would need to be root relative (or begin with a /).

Hope this helps. Thanks again for stopping by.

Amit Surti says:

Hi mate
How about social authority by moz
Chk this code here:https://github.com/seomoz/Social-Authority-SDK/blob/master/code-examples/php.php

is that working for you?
Thank You

Amit Surti says:

Now its working :)
After Enabling the openssl extension :)