We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

REST api NotFound problem

Hi,

I am testing the REST api code from here. https://docs.phalcon.io/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: https://localhost/phalcon/api/robots Not sure, what i am doing wrong here.

Phalcon v 1.2.4 PHP 5.3.17

Any thoughts? Thanks



1.5k
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();

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

Thanks Arif. Useful post.