Hello and welcome to my first article for the Brenelz Web Solutions blog! This article will cover how you can create a very simple API for any one of your projects. We are going to be using PHP and MySQL for the back end, and we will output our API data in two formats: XML or JSON.
API stand for Application Programming Interface. Put simply, it is a way for everyone (if you so choose) to access your website’s data. For example, let’s say that you have a website where users submit recipes they like. There is a lot of meta content that is associated to the initial submission, and you want all of this to be more accessible. This is a great example of a place where an API can do wonders. Take Twitter as an example, their success can be attributed largely to the success of their open API, providing developers with the “fire hose” to make their own apps and drive Twitter further.
For the purposes of this article, we will be using the situation that I mentioned above: you own a recipe database and you want those to be accessible to a larger audience.
We will accomplish this by providing this data in our API:
Let’s get started!
I recommend you use the following URL structure (or something similar):
Once you have this structure, create a new file in the *recipes* folder called *get.php*. This is the main file that will be requested by developers after our data. Add the following to this file:
<?php
if(isset($_GET['format']) &amp;amp;amp;&amp;amp;amp; intval($_GET['num'])) {
//Set our variables
$format = strtolower($_GET['format']);
$num = intval($_GET['num']);
//Connect to the Database
$con = mysql_connect('localhost', 'root', '') or die ('MySQL Error.');
mysql_select_db('api', $con) or die('MySQL Error.');
//Run our query
$result = mysql_query('SELECT * FROM recipes ORDER BY `recipe_id` DESC LIMIT ' . $num, $con) or die('MySQL Error.');
//Preapre our output
if($format == 'json') {
$recipes = array();
while($recipe = mysql_fetch_array($result, MYSQL_ASSOC)) {
$recipes[] = array('post'=>$recipe);
}
$output = json_encode(array('posts' => $recipes));
} elseif($format == 'xml') {
header('Content-type: text/xml');
$output = "<?xml version=\"1.0\"?>\n";
$output .= "<recipes>\n";
for($i = 0 ; $i < mysql_num_rows($result) ; $i++){
$row = mysql_fetch_assoc($result);
$output .= "<recipe> \n";
$output .= "<recipe_id>" . $row['recipe_id'] . "</recipe_id> \n";
$output .= "<recipe_name>" . $row['recipe_name'] . "</recipe_name> \n";
$output .= "<recipe_poster>" . $row['recipe_poster'] . "</recipe_poster> \n";
$output .= "<recipe_quick_info>" . $row['recipe_quick_info'] . "</recipe_quick_info> \n";
$output .= "<recipe_link>" . $row['recipe_link'] . "</recipe_link> \n";
$output .= "</recipe> \n";
}
$output .= "</recipes>";
} else {
die('Improper response format.');
}
//Output the output.
echo $output;
}
?>
This is the full version of the script, just to get it out there, now let’s explain it a little bit:
This one, luckily, is very simple. All we are doing is putting our data into an array, then using PHP’s very handy json_encode() function to encode the JSON. Here’s what I got with my dummy data outputting JSON:a into an array, then using PHP’s very handy _json_encode_ function to encode the JSON. Here’s what I got with my dummy data outputting JSON:
{"posts":[{"post":{"recipe_id":"20","recipe_name":"Grilled Flounder","recipe_poster":"Billy Bob","recipe_quick_info":"20 minutes prep, 40 minutes total time","recipe_link":"http:\/\/www.example.com\/"}},{"post":{"recipe_id":"19","recipe_name":"Grilled Flounder","recipe_poster":"Billy Bob","recipe_quick_info":"20 minutes prep, 40 minutes total time","recipe_link":"http:\/\/www.example.com\/"}},{"post":{"recipe_id":"18","recipe_name":"Grilled Flounder","recipe_poster":"Billy Bob","recipe_quick_info":"20 minutes prep, 40 minutes total time","recipe_link":"http:\/\/www.example.com\/"}},{"post":{"recipe_id":"17","recipe_name":"Grilled Flounder","recipe_poster":"Billy Bob","recipe_quick_info":"20 minutes prep, 40 minutes total time","recipe_link":"http:\/\/www.example.com\/"}},{"post":{"recipe_id":"16","recipe_name":"Grilled Flounder","recipe_poster":"Billy Bob","recipe_quick_info":"20 minutes prep, 40 minutes total time","recipe_link":"http:\/\/www.example.com\/"}}]}
The XML is a little more tricky, it requires the use of the very powerful (and scary) for() function. Here, we are basically saying this: As long as the variable $i is less than the number of rows that we returned, go ahead and add this to our $output variable. Once you’ve done that, add one to the $i variable. Here’s the output I got from this:
<?xml version="1.0"?> <recipes> <recipe> <recipe_id>20</recipe_id> <recipe_name>Grilled Flounder</recipe_name> <recipe_poster>Billy Bob</recipe_poster> <recipe_quick_info>20 minutes prep, 40 minutes total time</recipe_quick_info> <recipe_link>http://www.example.com/</recipe_link> </recipe> <recipe> <recipe_id>19</recipe_id> <recipe_name>Grilled Flounder</recipe_name> <recipe_poster>Billy Bob</recipe_poster> <recipe_quick_info>20 minutes prep, 40 minutes total time</recipe_quick_info> <recipe_link>http://www.example.com/</recipe_link> </recipe> <recipe> <recipe_id>18</recipe_id> <recipe_name>Grilled Flounder</recipe_name> <recipe_poster>Billy Bob</recipe_poster> <recipe_quick_info>20 minutes prep, 40 minutes total time</recipe_quick_info> <recipe_link>http://www.example.com/</recipe_link> </recipe> <recipe> <recipe_id>17</recipe_id> <recipe_name>Grilled Flounder</recipe_name> <recipe_poster>Billy Bob</recipe_poster> <recipe_quick_info>20 minutes prep, 40 minutes total time</recipe_quick_info> <recipe_link>http://www.example.com/</recipe_link> </recipe> <recipe> <recipe_id>16</recipe_id> <recipe_name>Grilled Flounder</recipe_name> <recipe_poster>Billy Bob</recipe_poster> <recipe_quick_info>20 minutes prep, 40 minutes total time</recipe_quick_info> <recipe_link>http://www.example.com/</recipe_link> </recipe> </recipes>
There are a few things I have left out of this article for the sake of simplicity. Once you have the basics of this figured out, you can add these yourself. A main thing I left out is the necessity of an API Key. If you want to manage who gets your data how, you must assign them an alphanumeric key of at least 32 characters, this will let you know who is accessing your data and you are also able to cut out just anyone from getting at your site. Another key part left out is the fact that you need to manage this API! Someone could just come in here, repeat this script over and over again and bring your website down. There are many free tools out there to limit your API usage, and one I highly recommend is 3scale. Twitter limits their API to 1000 requests per day, so you can get an idea of what you want your API limits to be from that.
Simple, wasn’t it? Using an API is a wonderful way to expand your user base as well as your content across the web. I hope this article has either helped you to learn something new or helped to put a concrete block under your knowledge. Thanks for reading!
No related posts.
Great post, thanks for that! +1 subscriber
Thanks for that, man!! It’s a great post, go on!
Great post Dixon, thanks for sharing!
Exactly what i really wants right now
[...] How to create a simple API with PHP and MySQL [...]
December 15th, 2009 at 1:33 am
Hi,
Nice post i like this post.
I have one problem regarding this.
When i am using xml format for output.
So how can i read that response XMl file.
and print that response on the site from where the request is made..
December 24th, 2009 at 5:20 am
Hi,
I got an error while executing the above script in my localhost. That is “XML Parsing Error: junk after document element”. How can i resolve this. Please help me. Thanx
[...] How to Create a Simple API with PHP and MySQL | Brenelz Web Design Solutions This article will cover how you can create a very simple API for any one of your projects. We are going to be using PHP and MySQL for the back end, and we will output our API data in two formats: XML or JSON. Possibly related posts: (automatically generated)From MySQL to jQuery, via PHP, XML & AjaxAuthenticating Twitter API calls with PHP & jQueryTUTORIAL: Create an Impressive Content Editing System with jQuery and PHPVisit from Thomson Reuters [...]
simple and informative, thanks alot.
Hi, nice post. Now, how do I implement security asking for a “api key” before posting, because in that way anyone can post without any restriction. I’ll keep reading you!
September 14th, 2010 at 9:43 am
this is awesome man!
September 20th, 2010 at 9:48 am
Hi,
the idea is awesome. But it doesn’t mean anything useful for a novice user like me. Where the XML file suppose to create? I appreciate if you can state it more clearly and step by step. Thanks.
Hello!
For some reason the xml only prints when i set the GET num to an odd number. When i set it to an even, it displays nothing.. why is that?
November 19th, 2010 at 3:24 am
Thanks for the article. Your JSON code in the tutorial is so long that a horizontal scroll bar appears and make the layout messed up.
February 2nd, 2011 at 11:48 am
I found http://www.gen-x-design.com/archives/create-a-rest-api-with-php/#comment-2714 API create class more good than the current. May be you like this one. I am working on both script which one give me good response will adapt that.
Thanks for this post this will help me a lot
Hey Guys,
I prepared this type of API application. May be It will use for others.
// myserver.php
addObjectMap($service, “urn:soapClass”);
// Einstellung, dass POST-Daten an den Service weiter gegeben werden
// preferene to forword POST data to the service
$ss->service ($HTTP_RAW_POST_DATA);
?>
// client place
path of the php file
require_once “SOAP/Client.php”;
// URI delivered to web service
$sc = new SOAP_Client(“http://localhost/myserver.php”);
$parameter = array(“xml”,”DV1eog9TJDdfdferffbU_1hmbkjhkjkT2DdkWs”);
header(“Content-type: text/xml”);
$result = $sc->call(“getDataList”, &$parameter,”urn:soapClass”);
echo $result;
?>
Good Post, Thanks for Sharing!!
i like this api. i want 3rd party developers to develop in-website apps using this api but they must be able test in on their servers. how do i share the users session with their website, my database uses the where clause e.g where u-email equals c-user-email
[...] How To Create a Simple API with PHP & MySQL: Step-by-step guide [...]
Hi,
I’ve just launched the PHP-API project on http://www.phpapi.org
I’ve tried to implement a skeleton upon which to build a fully functional system using a very easy to extend API (also the JavaScript connection with the API is implemented).
In the future I will add the API-Key so some of the modules/methods will be called only if an API-key is provided and an IP checker for the API to be called only from a specific IP for a specific API-Key.
Enjoy
Great post bro. Keep it .up.
useful post but fro future,,, Now i have to learn 1st how to use json API ![]()
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!