2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelでAPIを作ってみる

Posted at

はじめに

Laravelのお作法を勉強する為に、以前に素のPHPで作成したAPIもどきを移植してみたい。

コントローラーの作成

下記のコマンドで自動生成する。

php artisan make:controller SampleController --resource

ルーティングの追加

routes/api.php に下記を追加する。

Route::resource('sample','SampleController');

SampleControllerに処理を移植

class SampleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $url = '[GoogleスプレッドシートのURL]';

        $curl = curl_init();
        curl_setopt_array($curl,[
            CURLOPT_URL => $url,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_RETURNTRANSFER => true,
        ]);

        $result = curl_exec($curl);

        curl_close($curl);

        return response($result);
    }
}

ブラウザからアクセス

http://localhost/api/sample にアクセスする。

routes/api.php にルーティングを設定しているので、プレフィクスとして /api が付与されたURLとなる。

結果

[ { "id": 1, "name": "いわし", "value": 100 }, { "id": 2, "name": "うし", "value": 200 }, { "id": 3, "name": "ぶた", "value": 300 }, { "id": 4, "name": "とり", "value": 400 }, { "id": 5, "name": "くらげ", "value": 500 }, { "id": 6, "name": "いるか", "value": 600 }, { "id": 7, "name": "なくすと", "value": 700 }, { "id": 8, "name": "ららべる", "value": 800 } ]
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?