Advertisement

Make an iPhone App Using the Envato API

by

With the release of the new Envato Marketplace API, third-party developers now have access to a wealth of information to create all kinds of useful applications. This tutorial will teach you how to make your very own iPhone app using data from the new API. Even if you don't have an iPhone, you can still learn the basics about using PHP and JSON.

Before We Begin

The app we will be creating is based off of my iPhone app, Envato Marketplace Mobile. While we won't be recreating the entire app, this tutorial will give you a general idea on how it was created. This tutorial is aimed at PHP and JSON beginners and serves as a basis for creating more advanced PHP applications.

Using the API

Before we can start retrieving data using the API, we must learn how to go about accessing it. The API is split up into 5 parts:

  1. Version : determines what version of the API to use.
  2. Username : the user whose data you wish to access.
  3. API-key : similar to a password and is unique to each user and grants access to their data.
  4. set and format : determine what data to access and what format to provide it in.

For more information on the API, click here.

Step 1 - Accessing Our Data

Now that we know what is required to access the API, we are ready to put it into practice. Since we want others to use our awesome app, we need to get a username and API key on the fly; so we are going to retrieve some PHP variables from the browser.

if(isset($_GET['user']) && $_GET['user'] != "")
{
	$userName = $_GET['user'];
	if(isset($_GET['key']) && $_GET['key'] != "")
	{
		$apiKey = $_GET['key'];
	}
	else
	{
		echo 'Api key not set!';
		exit;
	}
}
else
{
	echo 'Username not set!';
	exit;
}

The above code checks to see if the variables user and key have been set - and exits if they haven't. It also checks to make sure that the global variable isn't empty.

Retrieving Our Data

Now that we have our required information, we can go ahead and use it to retrieve our data. To do this we will simply create a url using the format outlined in the introduction.

// Creates a string that will be used to access the API
$json_url = "http://marketplace.envato.com/api/edge/".$userName."/".$apiKey."/vitals+recent-sales.json";

Notice that we are using the "edge" version and are using our previous variables for the username and api-key. Finally, we are going to retrieve the vitals and recent sales data sets in the JSON format.

Now that we have created our url to access the API, we must read its contents so that they may be passed to the json_decode function - which requires an actual json data set, not just a url. So, let's go ahead and use the file_get_contents() function to read the contents of the url.

// Get the contents of the $json_url string
$json_contents = file_get_contents($json_url);

// A little error checking
if(!$json_contents)
{
	echo "Error: The JSON file could not be read. Please check your username and api key.";
	exit;
}

We are finally ready to convert the JSON data to an array so that we can use it in our application. To accomplish this task we will use the json_decode() function which will take the data from our $json_contents variable and output it to an array.

// Output our data to an array
$json_data = json_decode($json_contents, true);

We are using two parameters in this function, the first is the string we wish to decode, and the second tells the function to output the data as an array. That's it! We are now ready to show our data to the user.

Step 2 - Displaying Our Results

We've retrieved our data and now it's time to show it to the user. For the sake of simplicity we will be adding our frontend HTML code into the same file as our PHP code. So go ahead and add the standard HTML document code below your PHP code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Nettuts iPhone App - <?php echo $userName; ?></title>

<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<div id="header">My Nettuts iPhone App</div>
</body>
</html>

Notice that in the <title> tag, I added a simple PHP "echo" statement that will display the user's name in the browser's title bar.

Getting the Username and Balance

Let's go ahead and add a simple div that displays the username retrieved from the API. We could do this using the $userName variable like we used in the page title, however, using JSON is more exciting.

<div id="username"><?php echo $json_data['vitals']['username']; ?></div>

What the above code does is retrieve the username from the vitals array, which is an array within our $json_data array that was created earlier. Makes sense?

Here is the structure of the array used in the API example: Array ( [vitals] => Array ( [username] => ryan [balance] => 32.75 ) )

Next, we want to show the user his balance. This is done the same way as we displayed the username. This time, however, we will simply change from "username" to "balance". The rest is simply for layout and styling.

<div id="content">
<div class="line"><img src="bank_plus.png" alt="Balance" class="icon" />Balance: $<?php echo $json_data['vitals']['balance']; ?></div>
<h3>Recent Sales:</h3>

Listing Recent Sales

The last thing on our agenda is to display the most recent sales for a user. This is a little more complicated than the previous examples, however, if you've ever worked with arrays you should be able to handle it.

<?php
// List Recent Sales
$count = 1;
$salesArray = $json_data['recent-sales'];
foreach($salesArray as $value)
{
	if($count <= 10)
	{
		echo "<div class='line'><img src='plus.png' alt='Sale' class='icon' />Sold ".$value['item']." for <strong>$".$value['amount']."</strong></div>";
		$count = $count + 1;
	}
	else
	{
		break;
	}
}
?>
</div><!--End Content-->

There's a lot to digest here so lets start with the foreach statement. First we create a $salesArray from the recent-sales array within $json_data. This isn't necessary, but I think it looks cleaner. The foreach statement creates a $value for each row in the $salesArray array and allows us to pull information from each row. So, basically you use $value to get data from the row as the foreach statement loops through it.

Next up is the code which is executed each time the foreach statement goes through a row. Instead of showing all of the recent sales I only want to list ten, which is why, if the number of rows checked exceeds ten, it will break the loop. To change the number of rows the statement loops through, just change ten to the number you want. Actually displaying the rows is quite simple, as it requires just echoing out each row inside a div with a small icon. We use the $value to access the sale information from the array. We pull "item", which is the item title and "amount" which is the amount the author made on the sale. Finally "$count + 1" just increases the count of rows the statement has looped through. You should now be all set! Try loading the file on a testing server and see if it works!

If you don't have a Envato Marketplace account, you can use the example login:

  • user: ryan
  • key: 26k6otse2s586e4hcbzjy3quq830t3o4

Step 3 - Designing the Frontend

Adding CSS

Well, our new app works great, but it looks bad - which means it's time to break out some CSS. I assume you know enough to understand the following code as I won't be going into it except for a few things. #browser is used by the iPhone/Touch to make sure that if the page it is too small that it will fill the screen. body.lanscape #browser does the same, however, is for when the browser is in landscape mode.

body {
	background: #efefef;
	margin: 0px;
	padding: 0px;
	font-family: Helvetica;
	-webkit-touch-callout: none;
	-webkit-text-size-adjust: none;
	width: 100%;
	color: #2a2a2a;
}

#browser {
 	/* ensure we always fill the whole screen */
  	min-height: 416px;
}

body.landscape #browser {
  	min-height: 268px;
}

h3 {
	margin-bottom: 5px;
}

p {
	margin: 0 0 5px 0;
}

/*
	Layout
*/

#header {
	padding: 10px 5px 5px;
	height: 30px;
	color: #fff;
	font-size: 22px;
	background: url(header_bg.jpg) repeat-x;
}

#username {
	font-size: 18px;
	font-weight: bold;
	text-transform: uppercase;
	padding: 5px;
	/* WebKit supports text-shadow... so why not make it look pretty */
	text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5);
	color: #fff;
	background: #498929;
	border-top: 1px solid #85c952;
	border-bottom: 1px solid #34661c;
}

#content {
	padding: 5px;
	padding-top: 10px;
}

.icon { vertical-align: text-top; margin-right: 5px; }
.line { padding-bottom: 5px; border-bottom: 1px solid #cccccc; margin-bottom: 5px;}

iPhone Time

It's time to make your great app finally iPhone compatible. This is actually really easy and involves only one line of code.

<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">

Just add the above code right below the <title> tag and it should be the right size for your iPhone or iPod Touch. That code scales the page to the correct size for viewing on the iPhone. The last thing you may need to do is add a homepage icon so your app looks cool when someone adds your iPhone application as a webclip. To do this we add another small line of code that is similar to a favicon.

<link rel="apple-touch-icon" href="apple-touch-icon.png"/>

Well... we're all done! You can see the finished product below.

Conclusion

You've made it to the end. I hope this was a good introduction for those who are still in the beginning stages of using PHP and JSON. You're now ready to make your own killer app using the API and JSON in general.

Now remember, this tutorial is for beginners and those who need a jump-start for using the API.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Advertisement