LoginSignup
30
28

More than 5 years have passed since last update.

FuelPHPで他のサービスのWebAPIを利用する

Posted at

概要

FuelPHPで作成しているシステム内で、
他のサービスのAPIを利用したい場合の方法。

FuelPHPにあるパッケージを使って行う。

WebAPIを利用する

以下のようにできた。
サンプルコードで叩いているAPIは、Slackのもの。
https://api.slack.com/methods/users.list

fuel/app/tasks/test.php
<?php

namespace Fuel\Tasks;

class Test
{
    public function run()
    {
        // APIのトークン
        $token = '';

        // Request_Curlを生成
        // http://fuelphp.jp/docs/1.7/classes/request/curl.html
        $curl = \Request::forge('https://slack.com/api/users.list', 'curl');

        // HTTPメソッドを指定
        $curl->set_method('post');

        // パラメータを設定
        $curl->set_params(array('token' => $token));

        // 実行
        // $responseには、Responseインスタンスが入る
        // http://fuelphp.jp/docs/1.7/classes/response.html
        $response = $curl->execute()->response();

        // レスポンスコードチェック
        if ($response->status == 200)
        {
            // Formatクラスを利用して、JSONからPHPの配列に変換
            // http://fuelphp.com/docs/classes/format.html
            $data = \Format::forge($response->body,'json')->to_array();

            // 中身をチェック
            var_dump($data);
        }
    }
}

以下のコマンドで実行。

$ php oil refine test
30
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
28