Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

REST api NotFound problem

Hi,

I am testing the REST api code from here. http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html. But every time i run the code, i get "Sorry!, API not found." from notFound. Here is the code:

$di = new \Phalcon\DI\FactoryDefault();
//Set up the database service
$di->set('db', function(){
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "****",
        "password" => "****",
        "dbname" => "*****"
    ));
});

//Create and bind the DI to the application
$app = new \Phalcon\Mvc\Micro($di);

//Retrieves all robots
$app->get('/phalcon/api/robots', function() use ($app) {
    echo "<h1>Welcome!</h1>";
    $phql = "SELECT * FROM Robots ORDER BY name";
    $robots = $app->modelsManager->executeQuery($phql);

    $data = array();
    foreach ($robots as $robot) {
        $data[] = array(
            'id' => $robot->id,
            'name' => $robot->name,
        );
    }

    echo json_encode($data);
});
$app->notFound(function () use ($app) {
    $app->response->setStatusCode(404, "Not Found")->sendHeaders();
    echo 'Sorry! API not found.';
});
$app->handle();

And then access it via: http://localhost/phalcon/api/robots Not sure, what i am doing wrong here.

Phalcon v 1.2.4 PHP 5.3.17

Any thoughts? Thanks



927
Accepted
answer
edited Mar '14

I have solved the issue. 1st this line:

$app->get('/phalcon/api/robots', function() use ($app) {

should be:

$app->get('/robots', function() use ($app) {

Then it was the model issue because in the documentation page in REST API, it is not mentioned to register the models dir. So adding this would do the magic:

$loader = new \Phalcon\Loader();

$loader->registerDirs(array(
    __DIR__ . '/models/'
))->register();

http://phalcon-php-framework-documentation.readthedocs.org/en/1.0.0/reference/micro.html#models-in-micro-applications

Thanks Arif. Useful post.