phplaravelrestlaravel-4

Laravel retrieving data from REST API


Okay so I have a following situation:

The system I am building is retrieving data from a REST api and saving that data into a database. What I am wondering is how could this be implemented and where would behaviour like this go in sense of Laravels structure (controller, model etc.)? Does Laravel have a built in mechanism to retrieve data from external sources?


Solution

  • First you have to make routes in your app/routes.php

    /*
        API Routes
    */
    
    Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
    {
        Route::resource('pages', 'PagesController', array('only' => array('index', 'store', 'show', 'update', 'destroy')));
        Route::resource('users', 'UsersController');
    });
    

    Note: If you are not required authentication for API call, you can remove 'before' => 'auth.basic'

    Here you can access index, store, show, update and destroy methods from your PagesController.

    And the request urls will be,

    GET http://localhost/project/api/v1/pages // this will call index function
    POST http://localhost/project/api/v1/pages // this will call store function
    GET http://localhost/project/api/v1/pages/1 // this will call show method with 1 as arg
    PUT http://localhost/project/api/v1/pages/1 // this will call update with 1 as arg
    DELETE http://localhost/project/api/v1/pages/1 // this will call destroy with 1 as arg
    

    The command line CURL request will be like this (here the username and password are admin) and assumes that you have .htaccess file to remove index.php from url,

    curl --user admin:admin localhost/project/api/v1/pages    
    curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
    curl --user admin:admin localhost/project/api/v1/pages/2
    curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
    curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
    

    Next, you have two controllers named PagesController.php and UsersController.php in your app/controllers folder.

    The PagesController.php,

    <?php
    
    
    class PagesController extends BaseController {
    
    
        /**
         * Display a listing of the resource.
         *
         * @return Response
         * curl --user admin:admin localhost/project/api/v1/pages
         */
    
        public function index() {
    
            $pages = Page::all();;
    
            return Response::json(array(
                'status' => 'success',
                'pages' => $pages->toArray()),
                200
            );
        }
    
    
        /**
         * Store a newly created resource in storage.
         *
         * @return Response
         * curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
         */
    
        public function store() {
    
            // add some validation also
            $input = Input::all();
    
            $page = new Page;
    
            if ( $input['title'] ) {
                $page->title =$input['title'];
            }
            if ( $input['slug'] ) {
                $page->slug =$input['slug'];
            }
    
            $page->save();
    
            return Response::json(array(
                'error' => false,
                'pages' => $page->toArray()),
                200
            );
        }
    
        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return Response
         * curl --user admin:admin localhost/project/api/v1/pages/2
         */
    
        public function show($id) {
    
            $page = Page::where('id', $id)
                        ->take(1)
                        ->get();
    
            return Response::json(array(
                'status' => 'success',
                'pages' => $page->toArray()),
                200
            );
        }
    
    
        /**
         * Update the specified resource in storage.
         *
         * @param  int  $id
         * @return Response
         * curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
         */
    
        public function update($id) {
    
            $input = Input::all();
    
            $page = Page::find($id);
    
            if ( $input['title'] ) {
                $page->title =$input['title'];
            }
            if ( $input['slug'] ) {
                $page->slug =$input['slug'];
            }
    
            $page->save();
    
            return Response::json(array(
                'error' => false,
                'message' => 'Page Updated'),
                200
            );
        }
    
        /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return Response
         * curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
         */
    
        public function destroy($id) {
            $page = Page::find($id);
    
            $page->delete();
    
            return Response::json(array(
                'error' => false,
                'message' => 'Page Deleted'),
                200
            );
        }
    
    }
    

    Then you have model named Page which will use table named pages.

    <?php
    
    class Page extends Eloquent {
    }
    

    You can use Laravel4 Generators to create these resources using php artisan generator command. Read here.

    So using this route grouping you can use the same application to make API request and as a front-end.