cakephp-api icon indicating copy to clipboard operation
cakephp-api copied to clipboard

Espose api for plugins

Open rudy1976s opened this issue 3 years ago • 1 comments

I am trying to use the Api plugin for my application. My application highly relies on plugins, all located inside plugin folder of the application. I try to explain my scenario. I have a plugin calle Acme. I have created a PostsService which extends Api Service. In my plugin I have a folder Api -> Service -> Action -> PostsAction

namespace Acme\Api\Service\Action;

class PostsAction extends Action
{

    use LocatorAwareTrait;

    /**
     * @return bool
     */
    public function validates(): bool
    {
        return true;
    }

    /**
     * @return array
     */
    public function execute(): array
    {
        $params = Hash::get($this->getRoute(), '?');

        /** @var PostsTable $tablePosts */
        $tablePosts = $this->fetchTable('Posts');
        $query = $tablPosts->find();

        if (!empty($params['id'])) {
            $result = $query->where(['id' => $params['id']])->first();
        } else {
            $result = $query->toArray();
        }

        return [
            'posts' => $result
        ];
    }
}

Then i created a service under the namescape Acme/Service

namespace Acme\Service;

class PostsService extends ApiService {
    /**
     * @throws ReflectionException
     */
    public function initialize(): void
    {
        parent::initialize();

       $this->mapAction('list', PostsAction::class, ['method' => ['GET'], 'mapCors' => true]);

     }
}

Now I would like to test it 

`... /api/acme/posts/list`

What is the correct way to test it ? I have only route not found errors !

The documentation Routing is broken since years!!! please fix it or remove form the legend!!!

Thank you for any clarification.

Rudy

rudy1976s avatar Nov 24 '22 15:11 rudy1976s

Hi @rudy1976s, you can take a look here https://github.com/CakeDC/cakephp-api-cake4-demo/blob/master/config/api.php#L21 to see how a service is declared in a plugin and accessed.

Basically it depends on how you declare the service in config file api.php in your app.

In demo app it can be accessed with /api/blog2

Project: https://github.com/CakeDC/cakephp-api-cake4-demo

Please let us know if you have any other question.

ajibarra avatar Nov 25 '22 12:11 ajibarra