Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create website APIs

I get a lot of clients asking me about making mobile apps that connect to their websites to retrieve data, allow users to login, etc. Most of them have PHP-based sites, but don't have any clue about making APIs to interface with them. They ask me why I can't just connect directly to their SQL databases. I don't think that's a good thing to do from a mobile app. I would prefer they have some sort of API in place.

As far as PHP-based sites go, what are the best options when it comes to implementing an API for this purpose?

like image 419
gonzobrains Avatar asked Jul 07 '11 19:07

gonzobrains


People also ask

What is an API for a website?

API stands for Application Programming Interface. A Web API is an application programming interface for the Web. A Browser API can extend the functionality of a web browser.


2 Answers

Just make an api subdomain with a single controller, and a method for each specific task - output the data in json, and you're set:

http://api.theirsite.com/get-users
http://api.theirsite.com/get-news

etc...

like image 176
AlienWebguy Avatar answered Sep 30 '22 13:09

AlienWebguy


You want to look into RESTful web services. Have a look at the wiki for this here. Your client's need to essentially build PHP applications that serve the underlying data of their websites through some REST-compliant data type e.g. JSON, XML, SOAP, etc. There are a number of in-built PHP functions that enable the quick conversion of PHP data structures into these formats. This would enable you to build mobile apps that make HTTP requests to get data which it can then display in it's own unique way.

An example for a JSON powered service could be as follows:

$action = $_GET['action'];
switch($action) {
  case 'get-newest-products':
     echo json_encode(getNewestProducts());
     break;
  case 'get-best-products':
     echo json_encode(getBestProducts());
     break;
  .
  .
  .
  default:
     echo json_encode(array());
     break;
}

function getNewestProducts($limit = 10) {
  $rs = mysql_query("SELECT * FROM products ORDER BY created DESC LIMIT $limit");

  $products = array();
  if (mysql_num_rows($rs) > 0) {
    while ($obj = mysql_fetch_object($rs)) {
      $products[] $obj;
    }
  }
  return $products;
}

function getBestProducts($limit = 10) {
  $rs = mysql_query("SELECT * FROM products ORDER BY likes DESC LIMIT $limit");

  $products = array();
  if (mysql_num_rows($rs) > 0) {
    while ($obj = mysql_fetch_object($rs)) {
      $products[] $obj;
    }
  }
  return $products;
}

You could query the API as follows (with mod_rewrite on) http://myapi.mywebsite.com/get-newest-products

like image 45
GordyD Avatar answered Sep 30 '22 15:09

GordyD