0

I want to make a Restful API with JWT in order to be able to make calls to it.

I have this in /config/app.php:

return [
    'modules' => [
        'my-module' => \modules\Module::class,
        'demarketsjwt' => \demarkets\Module::class,
    ],
    // 'bootstrap' => ['demarketsjwt'],
    'components' => [
        'listingsDb' => [
            'class' => craft\db\Connection::class,
            'driverName' => 'mysql',
            'dsn' => 'mysql:host=localhost;dbname=' . getenv('DB_LISTINGS_DBNAME') . ';port=' . getenv('DB_LISTINGS_DBPORT') . ';',
            'username' => getenv('DB_LISTINGS_USER'),
            'password' => getenv('DB_LISTINGS_PASSWORD'),
            'charset' => 'utf8',
            'tablePrefix' => '',
            'enableSchemaCache' => !YII_DEBUG,
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'craft\web\UrlRule', 'controller' => 'user'],
            ],
        ],
    ],
];

and I have this in /controllers/UserController.php:

<?php

namespace app\controllers;

use Craft;
use craft\web\ActiveController;

class UserController extends ActiveController
{
    // public $modelClass = 'app\models\User';ç
    public function init()
    {
        parent::init();
        $now = time();
        $rows = Craft::$app->listingsDb->createCommand("SELECT * FROM table;")->execute();
        echo $rows;
    }
}

I am doing tests with Postman app but I cannot make it work. What am I doing wrong?

Thank you in advance for your kind help.

  • Anyone please? I need help. – Rafael Mora Oct 26 at 12:49
  • 1
    From a quick glance, you might need to disable CSRF routing on that controller. You can disable per controller by setting a public property of $enableCsrfValidation to false. You can also disable it globally (docs.craftcms.com/v3/config/…) but I would recommend only disabling it when necessary to maintain better security on your installation. – Jason McCallister Oct 26 at 16:39
  • Ok I will do that and get back to you. Thanks! – Rafael Mora Oct 26 at 16:57
  • @JasonMcCallister I tried what you suggest but I keep getting "error": "Template not found: users" What do you suggest? Where should the controller be placed? how should the controller be named? Thank you. – Rafael Mora Oct 26 at 23:01
  • 1
    Sounds like its looking for the web, not API request. Try setting the Accept header on Postman to be application/json. I have this example module working as an API request: github.com/jasonmccallister/craft-console/blob/master/src/… – Jason McCallister Oct 27 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.