How to Create a Simple API with PHP and MySQL

 

Introduction

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.

A Little Info, First!

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:

  • Recipe ID
  • Recipe Name
  • Recipe Poster
  • Recipe Quick Info (# of minutes prep, # of minutes total time)
  • Link to Recipe on our Websites

Let’s get started!

Into the Code…

I recommend you use the following URL structure (or something similar):

  • http://api.example.com/recipes/

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

  1. First, we need to get some data from the user: What format do you want? How many responses do you want?
  2. These are defined in the GET variables format and num. To start off our script, we check if these values are even supplied; if they’re not, the script won’t do anything. If they are both supplied, we move on by connecting to our database, running a relatively simple query to get all the rows, order them in descending order by their id, and limit the response to how many were requested.
  3. The majority of our script is taken up by the output processing. After we have our data selected into a variable, we need to get it out to the user. First, we check if the user wanted JSON or XML, and depending on that, we serve up the proper output. Let’s go a little more in depth on each of the output styles…

JSON

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\/"}}]}

XML

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>

A few notes…

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.

Conclusion

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!

Be Sociable, Share!

No related posts.

Written by Dixon Crews

Hey, I'm a high school student who really loves web design and development from North Carolina. I'd love to go to school to learn even more about design, possibly computer science, and eventually having a job designing and developing websites! Twitter | Website

 

23 Responses to “How to Create a Simple API with PHP and MySQL”

  1. Gareth Poole Says:

    December 1st, 2009 at 6:46 am

    Great post, thanks for that! +1 subscriber

  2. Menelion elensule Says:

    December 1st, 2009 at 9:16 am

    Thanks for that, man!! It’s a great post, go on!

  3. Drew Says:

    December 2nd, 2009 at 3:53 am

    Great post Dixon, thanks for sharing!

  4. faaiz Says:

    December 2nd, 2009 at 4:19 am

    Exactly what i really wants right now

  5. Notable Tech Posts – 2009.12.06 | The Life of Lew Ayotte Says:

    December 6th, 2009 at 2:01 pm

    [...] How to create a simple API with PHP and MySQL [...]

  6. Avi Says:

    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..

  7. Sha Says:

    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

  8. How to Create a Simple API with PHP and MySQL « Web Page Authority Blog Says:

    March 18th, 2010 at 4:01 pm

    [...] 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 [...]

  9. ahmed Says:

    May 19th, 2010 at 8:25 pm

    simple and informative, thanks alot.

  10. Peter Says:

    July 30th, 2010 at 4:34 pm

    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!

  11. beu Says:

    September 14th, 2010 at 9:43 am

    this is awesome man!

  12. Jimmy Liew Says:

    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.

  13. Robin Says:

    November 8th, 2010 at 3:00 pm

    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?

  14. Heri Hehe Says:

    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.

  15. sadamusic.com Says:

    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.

  16. Nikhil Says:

    June 10th, 2011 at 1:38 am

    Thanks for this post this will help me a lot

  17. Shaik Abdul Raheem Says:

    June 24th, 2011 at 7:56 am

    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;

    ?>

  18. Prakash Says:

    July 13th, 2011 at 1:16 pm

    Good Post, Thanks for Sharing!!

  19. Thapelo Says:

    July 21st, 2011 at 7:58 pm

    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

  20. How To Use Open APIs | Fast Fedora | Trevor Lohrbeer Says:

    August 11th, 2011 at 1:08 pm

    [...] How To Create a Simple API with PHP & MySQL: Step-by-step guide [...]

  21. Robert Doroftei Says:

    August 23rd, 2011 at 3:07 am

    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

  22. Sachin Says:

    April 18th, 2012 at 10:08 pm

    Great post bro. Keep it .up.

  23. Mukesh Says:

    April 22nd, 2012 at 11:07 am

    useful post but fro future,,, Now i have to learn 1st how to use json API ;)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
connect with me!