0

I am developing a PHP restful API which is returning a JSON response. This is currently for native mobile app consumption (iOS/Android).

My question, is it possible to use the same restful API for website consumption? or do I need to support HTML response from the restful API as well as JSON? How do you get a JSON response from a web service to display as a webpage? or do I need to implement output formatters as part of the framework to respond as HTML when required?

I have tried to search for answers to this question but I couldn't find any useful answer.

plawres
  • 313
  • 4
  • 19
  • 1
    You can use ajax for that. There are a lot of questions about that. Here is one of them: http://stackoverflow.com/questions/10941249/separate-rest-json-api-server-and-client – Franco Dec 25 '15 at 17:50
  • It's pretty standard nowadays to use a rest api/json to build up a website backend. Have a look at the various JavaScript Frameworks which will handle data binding, ajax etc etc . – jHilscher Dec 25 '15 at 18:03

2 Answers2

0

you can create API that returns XML and from XML using XSL construct HTML

This link gonna be helpful:

http://www.htmlgoodies.com/beyond/xml/converting-xml-to-html-using-xsl.html

volkinc
  • 2,143
  • 1
  • 15
  • 19
0

Emm... As theory, for example you can make it like this:

class MyOutput
{
    const CTX_HTML = 1;
    const CTX_JSON = 2;
    //const CTX_XML = 3;
    //const CTX_CLI = 4;
    //const CTX_ETC = N;

    private $_data = null;

    public function __construct()
    {
        $this->_data = new StdClass();
    }
    public function __set($prop, $value)
    {
        $this->_data->{$prop} = $value;
    }
    public function render($context)
    {
        if ($context == self::CTX_JSON) {
            header('Content-Type: application/json');
            echo json_encode($this->_data);
        } else {
            header('Content-Type: text/html');
            // TODO extract/pass data into layout/template
        }
    }
}


$Output = new MyOutput();

$Output->foo = 1;
$Output->bar = 2;
$Output->render(MyOutput::CTX_JSON);
$Output->render(MyOutput::CTX_HTML);

But i think API should be place on separated host. Because this is different applications.

Deep
  • 2,472
  • 2
  • 15
  • 25