LoginSignup
66
78

More than 3 years have passed since last update.

laravel でAPI作成

Last updated at Posted at 2020-04-18

LaravelでAPIを作成する

CRUDとか、ルーティングとか、なんとなくはわかってるけど、
「APIを叩く」と言われても、APIを…叩く…?というレベルでピンとこない初学者が
とりあえず見様見真似でAPIを作成したので備忘録。

API作成の手順

1. テーブル(マイグレーションファイル)を作る
2. モデルを作る
3. コントローラーを作る
4. APIのルーティングを追加する

案外これだけ。API作るってどんなけ難しいんや…と思ってましたが
普通の実装となんら変わらんでした。データをJSON形式で返すのでViewは不要。

1. テーブル作成

早速、順を追って作成していきます。
今回はサーバ側でバージョン管理用のテーブルを作成して、
そのデータを別媒体でも取得できるような簡単なAPIを作成しました。

$ php artisan make:migration create_ver_table

migrationファイルの中身はこんな感じ。
最新バージョンと最低バージョンあればいいでしょってことでカラムは至ってシンプルに。

create_ver_table.php
    public function up()
    {
        Schema::create('ver', function (Blueprint $table) {
            $table->increments('id');
            $table->string('version');
            $table->string('min_version');
            $table->timestamps();
        });
    }

migration 実行してテーブル作ります。

$ php artisan make:migrate

2. モデル作成

テーブルが作成できたら作ったテーブルのデータにアクセスするためにモデルを作ります。

$ php artisan make:model Ver
Ver.php
class Ver extends Model
{
    protected $table = 'ver';
    protected $dates =  ['created_at', 'updated_at'];
    protected $fillable = ['id', 'version', 'min_version'];
}

3. コントローラー作成

コントローラ を作って処理を書いていきます。
make:controllerコマンド実行時に、引数に--apiを入れると
APIに不要なメソッドを除外した状態でリソースコントローラーを作ってくれるらしいです。
今回はindexメソッドしか使わないので普通にコマンド実行。

$ php artisan make:controller API/VerController
Controller
use App\Ver;   // 追加

class VerController extends Controller
{
    public function index()
    {
       try {
            $version = Ver::first();
            $result = [
                'result'      => true,
                'version'     => $version->version,
                'min_version' => $version->min_version
            ];
        } catch(\Exception $e){
            $result = [
                'result' => false,
                'error' => [
                    'messages' => [$e->getMessage()]
                ],
            ];
            return $this->resConversionJson($result, $e->getCode());
        }
        return $this->resConversionJson($result);
    }

    private function resConversionJson($result, $statusCode=200)
    {
        if(empty($statusCode) || $statusCode < 100 || $statusCode >= 600){
            $statusCode = 500;
        }
        return response()->json($result, $statusCode, ['Content-Type' => 'application/json'], JSON_UNESCAPED_SLASHES);
    }
}

$versions = Ver::first();:verテーブルのデータの最初の一つだけ取得。
                 データが複数の場合は全取得にしてforeach処理が必要。
$result = [...]:APIで送りたいデータをこの中で定義しています。
return response()->json(...);:結果をjsonに変換する処理。
JSON_UNESCAPED_SLASHES:こいつでスラッシュのエスケープを抑止できるようです。

4. ルーティング追加

ここまで来たらあと一息。ルーティングを追加します。
APIのルーティングはroutes/api.phpに記載します。

api.php
 Route::get('ver','API\VerController@index');

設定したurlにアクセスして、APIの中身が確認できたらAPI作成完了です。
↑の場合だとhttp://localhost/api/verにアクセスしたら画面にこんな感じで表示されます。
  {"result":true,"version":"1.1.1","min_version":"1.1.0"}
これがいわゆる「API叩く」ってことらしいです。

振り返ってみると簡単な気もするけどまだ理解しきれていない部分もあって難しい...
以上でした!

参考サイト

66
78
2

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
66
78