Phalcon PHP - RESTful API

5.5k views Asked by At

I am building a RESTful API using Phalcon PHP (micro). This framework is new to me and I am not experienced with it.

I would like to find some resource which provides best practices and live examples of how to create such an API in a right way.

The amount of endpoints is getting bigger and bigger and I feel I am going in the wrong direction.

http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html I had a look in this tutorial but it is too simple and does not cover all my questions. My API will be much more bigger.

2

There are 2 answers

0
Oliver McPhee On BEST ANSWER

To be honest, it depends on how strict your REST API is going to be. If you plan on publishing your endpoints in API documentation then this is a good tutorial: http://www.restapitutorial.com/

However, strictly speaking that isn't REST. (But its still the most common type of API out there - for example Google Drive follows that approach).

It should be noted that IF you have LOTS of resources in this approach, then you'll have LOTS of endpoints. You can't get away from that.

If you want to limit the amount of endpoints you publish, then you'll want to research HATEOAS (Hypermedia as the Engine of Application State). This is actually what is required to build a proper REST API.

Explained in plain english...

Typically, all you need to do is have 1 root endpoint. Then, inside the JSON payload for that initial resource, you include links to other resources of your API. These links should be the next states that you can transition to with the data you have available.

This way, an API is 'explored' just like you would a webpage. I.E. you'd go to a website homepage and you'd click a link to go to the next page. Similarly, you'd go to your root API url and choose to follow a link returned by it.

There is also a convention called HAL that is used for structuring your JSON responses: http://stateless.co/hal_specification.html

Cheer, Ollie

0
galki On

There is no right way but here are two patterns I came across. They are both based on the notion that your actions will be named after the request methods: getAction, postAction, putAction, patchAction, deleteAction.

Pattern One is to create a separate module for the RESTful API. Pattern Two (below) is to have both base and RESTful calls access the same module/controller.

// base 
$router->add('/:module/:controller/:action/:params', [
    'namespace' => 'App\ModuleName\Controllers',
    'module' => 1,
    'controller' => 2,
    'action' => 3,
    'params' => 4
]);

// restful (set action by request method)
$request = new \Phalcon\Http\Request();
$action = $request->getMethod();
$router->add('/:module/:controller/:params', [
    'namespace' => 'App\ModuleName\Controllers',
    'module' => 1,
    'controller' => 2,
    'params' => 3,
    'action' => $action
]);

Bonus! Here is a bunch of other examples for your reference.