Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Build a RESTful API
  • Hello everyone! I am very excited using FuelPHP and it works great so far so thank you for this wonderful framework! Anyway.. I would like to build a simple, secure RESTful API with fuelPHP. My idea is to develop a classical website BUT would like to use lot of AJAX (i already know how to use REST controllers and jquery it works fine) but in the mean time build the API. Basically, i would like to build an API that i can call from my website (in the same fuelPHP app) or another one or even from a mobile app for instance. The problem is that i don't know how to develop this in a good way... an other problem is that i am afraid (from a mobile app for instance) somebody could directly access to the API and spam it... how to secure my API, is there something to handle that with REST controllers. The best thing would be to see a RESTful API developped in fuelPHP or a tutorial to help me.. i'm a bit lost to do this stuff and would like to do it in the best way... Thanks in advance, Regards.
  • Thanks for the update, only one controller could be nice indeed (i like to centralize the access). For now, i just need a private API not a public one so i don't have to generate api key / secret key for each user, only a secret key (access token). I don't need anyone use my API to create a new app based on it so will see how i do that (oAuth or not) but oAuth seems to be more stable/secure than a "from scratch" solution. Depending on my needs, if it's more faster to do it from scratch for a simple (but secure) private API, perhaps i'll do that but i definitively wil try the oAuth fuelPHP components :)
  • I don't think it's easy to write a tutorial for this, as there are numerous ways to do it. I can only tell you how we do it, and why. We don't mix frontend and API in the same application, but we run them on different virtual hosts. We also don't mix API versions, a new version of the API gets a new virtual host. Reason for this is that you can develop your API independent of your front-end application, and it provides much better scalability when you get more applications using your API then only your own frontend application. It also allows you to switch applications to a new version of the API without impacting applications that still use the old one. We also use the API in the frontend server side (using Curl requests), this allows you to create frontend applications that don't have a direct data interface (i.e. the models don't interact with the database, but they do Curl requests to interact with the API). The servers running the API interfaces are buried deep in the datacenter, behind lots of security measures. If for some reason your frontend get's hacked, there is not a single byte of data to be had. Any data not exposed by the API can not be accessed, and given the location of the API servers, hacking them will be a lot more complex. For authentication we use another API server that publishes an OAuth2 interface, and in the backend communicates with whatever authentication system is used (usually Active Directory or LDAP). The OAuth2 scope passed in the login request defines the level of access required (we have apps where users have different roles, the apps need to know which role a user is performing, and the Auth server needs to check if the user can perform that role). An OAuth2 login returns (amongst other things) an access token that can be used to validate API requests. We pass this token in every API call, the API server will validate it with the OAuth2 server before giving access to the API. This is basically the same mechanism that protects the API's of Google, Facebook, etc. You can find more information here: https://developers.google.com/accounts/docs/OAuth2
  • Ok thanks a lot, that answers some questions i had ;) I can be more accurate maybe.. i would like to create a website AND a mobile app that can access the same data :) so maybe i could create a very simple (but secure) API (just one user perhaps). Do i have to use oAuth2 for any API? I heard that it's pretty tricky to implement :)
  • It can be complicated. Fortunately:
    OAuth server: https://github.com/philsturgeon/fuel-oauth-provider
    OAuth client: https://github.com/fuel-packages/fuel-oauth2 Haven't used the provider yet (but I know Phil does), the client works perfectly.
  • Thanks a lot, looks awesome :) i will give you a feedback about the provider.
  • I also have an API that is used to access my site through a mobile app. As it stands now all i basically do is create unique session keys and compare them to saved keys in the database but I'm also looking into how to implement Oauth with my mobile phonegap/jqmobile app. For example he's my router for my api rest controller
     public function router($resource, array $arguments) {
            \Config::load('rest', true);
    
            $this->format = 'json';
    
            // If they call user, go to $this->post_user();
            $controller_method = strtolower(\Input::method()) . '_' . $resource;
    
            //is this a valid method
            if (method_exists($this, $controller_method)) {
                if ($controller_method == 'post_login') {
                    call_user_func_array(array($this, 'post_login'), $arguments);
                } else {
                    
                    $session_key = Input::post('session_key');
                    
                    $session = Model_Session::find()
                            ->where('session_key', $session_key)
                            ->get_one();
    
                    if (!$session) {
                        $this->response(array('status' => 0, 'error' => 'Not Authorized'), 401);
                        return;
                    } else {
                        call_user_func_array(array($this, $controller_method), $arguments);
                    }
                }
            } else {
                $this->response(array('status' => 0, 'error' => 'Invalid method'), 405);
                return;
            }
        }
    
    
  • Thank you for this snippet. So you basically use only one controller for the whole API and create a method for each function you need? Perhaps it's better to create a REST controller for each entity? What i possibly see is a folder api and then
    -A User REST controller with login/logout/register/getProfile/updateProfile/deleteProfile methods
    -A specific App core REST controller in order to give the general function from my app (for instance get a random profile from the database with some parameters) When i give the access to other methods except login/register i check a kind of session_token / access token (access token if oAuth) but first i think i will use a simple system which check the session_token generated by the Auth native controller in fuelPHP (typically a person registers to the website and have a single/unique session_token in the database). This token could also be useful for a "remember me" function i guess. Do you think it's the right way to do it?
  • Yes I have one rest controller called API for all the methods, why would it be better to have multiple controllers? On the client side code you're going to need to point your request to the specific controller, but the routing in the controller is already going to take care of that. If you have data that is going to be public I can see having a controller just for that, but atleast for my site everything is based off of being logged in to a certain account. I was writing an OAuth2 rest controller for app validation, but then isn't OAuth more for checking that a specific client app is authorized to see data? I'm writing my own mobile apps for the API and its not public so I don't think OAuth would do anything security wise. I just have a static access key to get in the api. Are you writing your api client interface too? Or just developing the server side code? I'm using phonegap/jquery mobile and feel like I'm not securing it properly.
  • OAuth provides both authentication and authorisation. Twitter for example uses it to determine if an app has access to your timeline, your followers, if it may tweet in your name, etc.
  • Hey Naturel, I'd be interested to hear how this worked out for you.

    I'm building a similar project - an API with all of the data interaction that the mobile app and front-end website GET/POST/etc. to. It was a little confusing to architect in the beginning, but it's working out pretty well now.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion