Laravel从REST API检索数据

Tom*_*rho 28 php api rest laravel laravel-4

好的,我有以下情况:

我正在构建的系统是从REST API检索数据并将数据保存到数据库中.我想知道的是如何实现这一点以及这样的行为在Laravels结构(控制器,模型等)意义上的位置?Laravel是否有内置机制从外部源检索数据?

fid*_*per 41

编辑: Buzz的更新时间已超过一年,现在推荐使用Guzzle,请参阅Mohammed Safeer的回答.


我使用Buzz包来发出API请求.

您可以通过将此包添加到文件中的require部分来添加此包composer.json.

{
    require: {
        "kriswallsmith/buzz": "dev-master"
    }
}
Run Code Online (Sandbox Code Playgroud)

然后运行composer update以安装它.

然后在Laravel中,您可以将其包装在一个类(可能是类似于存储库的类)中,该类处理API请求并返回您的应用程序要使用的数据.

<?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
    }

}
Run Code Online (Sandbox Code Playgroud)

注意:这是伪代码.您需要创建一个适合您需求的类,并执行您想要/需要的任何花哨依赖注入或代码体系结构.

正如@Netbulae所指出的,存储库可能对您有所帮助.他链接文章是一个很好的起点.本文与您的代码之间的唯一区别是,您不是使用Eloquent模型从数据库获取数据,而是发出API请求并将结果转换为应用程序可以使用的一组数组/对象使用(基本上,只是数据存储是不同的,这是首先打扰存储库类的好处之一).

  • 我不明白为什么选择其他答案作为正确的答案.当然,问题是如何查询远程RESTful API而不是构建一个. (13认同)
  • 嗡嗡声似乎被抛弃了.也许你应该使用guzzle代替. (2认同)

Moh*_*eer 25

我们可以在Laravel中使用Guzzle包,它是一个发送HTTP请求的PHP HTTP客户端.

你可以通过作曲家安装Guzzle

composer require guzzlehttp/guzzle:~6.0
Run Code Online (Sandbox Code Playgroud)

或者您可以将Guzzle指定为项目现有composer.json中的依赖项

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}
Run Code Online (Sandbox Code Playgroud)

使用Guzzle的laravel 5中的示例代码如下所示,

use GuzzleHttp\Client;
class yourController extends Controller {

    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);

        $result= $res->getBody();
        dd($result);

}
Run Code Online (Sandbox Code Playgroud)

  • 甚至laravel文档建议在项目中使用mandrill或mailgun API时使用Guzzle,并且guzzle易于使用和安装. (2认同)

dev*_*evo 8

首先,你必须在你的路线 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');
});
Run Code Online (Sandbox Code Playgroud)

注意:如果您不需要API调用的身份验证,则可以删除'before' => 'auth.basic'

在这里,您可以访问index, store, show, update and destroy您的方法PagesController.

请求网址将是,

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
Run Code Online (Sandbox Code Playgroud)

命令行CURL请求将是这样的(这里是用户名和密码admin)并假设您有要从url中.htaccess删除的文件index.php,

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
Run Code Online (Sandbox Code Playgroud)

接下来,您有一个名为两个控制器PagesController.phpUsersController.php您的app/controllers文件夹中.

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
        );
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你有一个名为的模型Page将使用名为table的表pages.

<?php

class Page extends Eloquent {
}
Run Code Online (Sandbox Code Playgroud)

您可以使用Laravel4 Generators使用php artisan generator命令创建这些资源.阅读这里.

因此,使用此路由分组,您可以使用相同的应用程序来发出API请求并作为前端.

  • 我无法看到如何创建模型以从API检索数据.您的所有答案都是关于创建API和利用Laravel资源控制器.问的很热. (4认同)
  • 这是OP提出的要求吗?看来他问**从**检索**,你回答了关于创建API的问题 (2认同)

tsv*_*iko 6

您可以选择使用的内容:

  1. 喝酒失控
  2. 卷曲
  3. file_get_contents:

    $json = json_decode(file_get_contents('http://host.com/api/v1/users/1'), true);
    
    Run Code Online (Sandbox Code Playgroud)

介绍人