PHP API Development: Dreaming Of Your Own API? Make It Possible Today!

I have often dreamed of creating an API for one of my sites but I’ve always set it aside as I thought it would be too much work to do. One day I just decided it’s time to do the research and get started with building my own API and it wasn’t as difficult as I thought.

So you are probably eager to start with this one? OK I’ll show you how!

First thing, you need to have a database in place with data. I’m not going to show you how to build a database with tables as it’s one of the basics you need to know. I’m sure most of you are past the basics.

The first part of the code

if($_GET['q'] == "all" && $_GET['type'] == 'json'){

//get a connection to mysql

$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());

//select your database table

mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());

//get your results with a mysql query

$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());

//run a while loop get your data.

while($place = mysql_fetch_array($result, MYSQL_ASSOC)) {

$places[] = array('location'=>$place);

}

$output = json_encode(array('map' => $places));

echo $output;

mysql_close($con);

}

First off we select all data from our database. You can set search criteria for different results for example for getting particular users details from your social network, but in this example we select everything.

In the example above I select all data from my android maps app database for locations and places. We then do some JSON encoding to put the data in the correct format. All you need to do to use the output data is to grab it and use a JSON decode method

The output of the data in JSON format.

{"map":[{"location":{"idgmaps":"15","lat":"-25.926813935317035","lon":"27.828453713378963","address":"cradle of human kind","title":"Cradle of Humankind","description":"The 47 000-hectare Cradle of Humankind is blessed with a greater wealth of early human history than almost any other place on earth. \r\n\r\nThe Cradle contains more than twelve major fossil sites and dozens of minor ones. The Maropeng Visitors Centre at the Cradle of Humankind (near Johannesburg) was opened in 2005. The tumular building is designed to look like an ancient burial mound, though from the rear it looks like a modern structure. \r\n\r\nInside, a journey through the evolution of life is presented, and the architecture is symbolic of this journey. Maropeng means returning to the place of origin in Setswana, the local indigenous language. It is a reminder that the ancestors of all humans, wherever they live today, originally came from Africa.","tags":"Maropeng, Cradle of Human Kind, Early Humans","idurls":"17","url_name":"Early humans","url":"http:\/\/newhistory.co.za\/part-1-chapter-1-early-humans\/"}}

The second part of the code

In this part we switch the data format to output XML.


elseif($_GET['q'] == "all" && $_GET['type'] == 'xml'){

//get a connection to mysql

$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());

//select your database table

mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());

//get your results with a mysql query

$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());

//run a while loop get your data.

while($location = mysql_fetch_array($result)) {

$output = '<?xml version="1.0" encoding="utf-8"?>';
$output .= '<data>';
$output .= "<lat>".$location['lat']."</lat>";
$output .= "<long>.".$location['lon']."</long>";
$output .= "<description>.".$location['description']."</description>";
$output .= '</data>';
print $output;

}

mysql_close($con);

}else{

echo "<h1>No results to show for you query</h1>";

}

The second par t of the code we switched over to XML output. The only big difference is the elseif and the XML tags I added in the while loop.

Here’s the complete code.


<?php

if($_GET['q'] == "all" && $_GET['type'] == 'json'){
//get a connection to mysql
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());

//run a while loop get your data.
while($place = mysql_fetch_array($result, MYSQL_ASSOC)) {

$places[] = array('location'=>$place);

}

$output = json_encode(array('map' => $places));
echo $output;
mysql_close($con);

}elseif($_GET['q'] == "all" && $_GET['type'] == 'xml'){

//get a connection to mysql
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result2 = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());

//run a while loop get your data.
while($location = mysql_fetch_array($result2)) {

$output = '<?xml version="1.0" encoding="utf-8"?>';
$output .= '<data>';
$output .= "<lat>".$location['lat']."</lat>";
$output .= "<long>.".$location['lon']."</long>";
$output .= "<description>.".$location['description']."</description>";
$output .= '</data>';
echo $output;
}

mysql_close($con);

}else{

echo "<h1>No results to show for you query</h1>";
}
?>

That’s it, did you expect more?

As you can see it’s straight forward and simple to build your very own API system for your own site. Nothing to it really even a monkey can do this 😉

Hope you enjoyed this tutorial. Please leave a comment, let me know what you think?

Related Posts:

  • rss
  • email
  • rss
  • email
I'm a full time PHP developer and I just love all things web related. If you need help I'm your guy.

6 Responses to PHP API Development: Dreaming Of Your Own API? Make It Possible Today!

  1. Interesting Article but not exactly an API, if you have included user management and authenticating sessions then it would have been more realistic.

    Also using GET limits your input variables you should use post.

  2. Morné says:

    Hi Matthew,

    Thanks, yes user management is optional of course :). I could build in some authentication which would help with limiting people from hogging a server and you could manage things like the amount of requests and so on.

    I used the GET just to get an better idea of how things work, but yes POST would be much better in certain situations.

    Thanks for the comment :)

  3. Patilraj21 says:

    hi, what about the pagination in XML api , what is use of _GET[‘all’] ?

  4. Morné says:

    Hi There,

    I guess i did not really think about it enough when I used the GET[‘all’] part. You could add extra get values for total and page limits to improve it.

    In my situation the get all part was for one of my Google map projects on android to get the map populated with all the pin data.

    Thanks for your comment.

  5. Ari Susanto says:

    How about the client side code? Is there any example?

  6. Abhishek Prakash says:

    Hi, Nice Post. I have a question – I have to develop an eCommerce website. I am thinking of angularjs as a front end and restful Laravel api as the backend. Is it a right choice?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>