Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 451
Tomkarho Avatar asked Oct 01 '13 19:10

Tomkarho


People also ask

Does Laravel have REST API?

Laravel lets you easily and quickly build RESTful APIs. This could be the back-end to a front-end web app, a data source for a mobile app, or a service for other apps or APIs.

What is Apiresource in Laravel?

Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON. Basically you can generate a nice json formatted data right from Eloquent.


1 Answers

Edit: Buzz hasn't been updated for over a year, it's recomended to now use Guzzle, see Mohammed Safeer's answer.


I have used Buzz package in order to make API requests.

You can add this package by adding it to the require section in your composer.json file.

{     require: {         "kriswallsmith/buzz": "dev-master"     } } 

Then run composer update to get it installed.

Then in Laravel you can wrap it in a class (perhaps a repository-like class) that handles making API request and returning data for your app to use.

<?php namespace My\App\Service;  class SomeApi {      public function __construct($buzz)     {         $this->client = $buzz;     }      public function getAllWidgets()     {         $data = $this->client->get('http://api.example.com/all.json');         // Do things with data, etc etc     }  } 

Note: This is pseudocode. You'll need to create a class that works for your needs, and do any fancy dependency injection or code architecture that you want/need.

As @Netbulae pointed out, a Repository might help you. The article he linked is a great place to start. The only difference between the article and what your code will do is that instead of using an Eloquent model to get your data from your database, you're making an API request and transforming the result into a set of arrays/objects that your application can use (Essentially, just the data storage is different, which is one of the benefits of bothering with a repository class in the first place).

like image 193
fideloper Avatar answered Sep 23 '22 03:09

fideloper