1

I am trying to create app using ionic framework for which I need to create a api connectivity. My requirement is that I need to use firebase. I have gone thru the firebase.com. I learnt how they are giving us a url so that api route connection is done. But I want to create my own api service (simulator) to give the required json as output?

How could I do it?

Regards, Sabarisri

Nikola
  • 14,888
  • 21
  • 101
  • 165
sabari
  • 2,595
  • 5
  • 28
  • 44

1 Answers1

2

I wrote a detailed post on how you can post data from Ionic app to PHP server (and read the response back) and you can view it here.

However, as a tl;dr this is how you would approach this:

On your server you would make a PHP file like this:

<?php
    //http://stackoverflow.com/questions/18382740/cors-not-working-php
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }


    //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
    $postdata = file_get_contents("php://input");
    if (isset($postdata)) {
        $request = json_decode($postdata);
        $username = $request->username;

        if ($username != "") {
            echo "Server returns: " . $username;
        }
        else {
            echo "Empty username parameter!";
        }
    }
    else {
        echo "Not called properly with username parameter!";
    }
?>

Please note that I'm using PHP in this example, but basically it's more/less the same in any other language. Just google for "How to create an API in xyz language" and you should get more than enough tutorials online on how to achieve this. Of course, the exact code here would have to suit your exact situation, and here you would basically either do some database queries or fetch some other data and then serve it as json.

To interact with this API you can simply use Angular's $http service like this:

controller('AppCtrl', function($scope, $http) {
    $scope.data = {};

    $scope.submit = function(){
        var link = 'http://your-server.com/api.php';

        $http.post(link, {data : $scope.data}).then(function (res){
            $scope.response = res.data;
        });
    };
});
Nikola
  • 14,888
  • 21
  • 101
  • 165