【问题标题】:Laravel retrieving data from REST APILaravel 从 REST API 检索数据
【发布时间】:2013-10-08 01:48:20
【问题描述】:

好的,所以我有以下情况:

我正在构建的系统正在从 REST api 检索数据并将该数据保存到数据库中。我想知道的是如何实现这一点,以及这种行为在 Laravel 结构(控制器、模型等)的意义上会在哪里? Laravel 是否具有从外部资源检索数据的内置机制?

【问题讨论】:

  • 剧透:所选答案完全被误导。跳到第二个,有更多的投票,以准确了解如何检索数据:)
  • 现在即使这样也改变了@igorsantos07 和this one is the preferred method

标签: php api rest laravel laravel-4


【解决方案1】:

尝试查看外部 API 的手册。在那里您将找到有关如何检索信息的信息。

那么最好的计划是构建一个接口。 看一下这个: http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/

这取决于你如何使用 php 来解决这个问题。

【讨论】:

    【解决方案2】:

    编辑: Buzz一年多没更新了,现在推荐使用Guzzle,见Mohammed Safeer's的回答。


    我使用Buzz package 来发出 API 请求。

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

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

    然后运行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
        }
    
    }
    

    注意:这是伪代码。您需要创建一个满足您需求的类,并执行您想要/需要的任何花哨的依赖注入或代码架构。

    正如@Netbulae 指出的那样,存储库可能会对您有所帮助。 article he linked 是一个很好的起点。本文与您的代码将执行的操作之间的唯一区别是,您不是使用 Eloquent 模型从数据库中获取数据,而是发出 API 请求并将结果转换为应用程序可以执行的一组数组/对象使用(本质上,只是数据存储不同,这是首先使用存储库类的好处之一)。

    【讨论】:

    • 我不明白为什么选择其他答案作为正确答案。当然,问题是关于查询远程 RESTful API 而不是构建一个。
    • 标记为正确的答案显示了如何构建应用程序并保护应用程序以使用 API 并保存检索到的数据,因此它确实回答了问题并且几乎没有超出其范围,但在相当具体方式。但是,我也更喜欢 fideloper 的答案,因为它更普遍(即使有特定的包推荐!)
    • 问题是“[..] 从 REST api [..] 检索数据 [..] Laravel 是否具有从外部来源检索数据的内置机制?”这让我认为有人问如何从 Laravel 应用程序调用其他 Web 服务。但是接受的答案从另一方面描述了它 - 如何使用 curl 从 Laravel 应用程序中检索数据。还有一点——不要盲目运行composer update——它会更新你所有的库,可能会破坏一些东西。如果你想稳定,总是更喜欢使用composer require vendor/library 方法。
    • Buzz 似乎被抛弃了。也许你应该改用 guzzle。
    【解决方案3】:

    首先,您必须在 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');
    });
    

    注意:如果API调用不需要认证,可以去掉'before' =&gt; 'auth.basic'

    您可以在此处从您的PagesController 访问index, store, show, update and destroy 方法。

    请求的 url 将是,

    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
    

    命令行 CURL 请求将是这样的(这里的用户名和密码是 admin)并假设您有 .htaccess 文件从 url 中删除 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
    

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

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

    然后你有一个名为 Page 的模型,它将使用名为 pages 的表。

    <?php
    
    class Page extends Eloquent {
    }
    

    您可以使用 Laravel4 生成器使用 php artisan generator 命令创建这些资源。阅读here

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

    【讨论】:

    • 如果将值作为 json-array 发送到 'update()' 想要保存该数组中的所有字段,我们如何做到这一点而不是一一提及..$page->title = $input['title'];$page->slug =$input['slug'];等等?
    • @brito 一个简单的解决方案foreach ($input as $key =&gt; $value) { $page-&gt;$key = $value; } 这可能有效。
    • 这是 OP 要求的吗?似乎他询问了 检索,而您回答了有关创建 API 的问题
    • @igorsantos07 试图解释包括检索在内的完整步骤。
    • 我在任何地方都看不到如何创建模型以从 API 中检索数据。你所有的答案都是关于创建 API 和利用 Laravel 资源控制器。问的很热。
    【解决方案4】:

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

    你可以通过 composer 安装 Guzzle

    composer require guzzlehttp/guzzle:~6.0
    

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

    {
       "require": {
          "guzzlehttp/guzzle": "~6.0"
       }
    }
    

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

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

    【讨论】:

    • 连 laravel 文档都建议在项目中使用 mandrill 或 mailgun API 时使用 Guzzle,guzzle 易于使用和安装。
    【解决方案5】:

    你可以选择使用什么:

    1. 狂饮
    2. 卷曲
    3. 文件获取内容:

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

    Referrer

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多