1
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 3 years have passed since last update.

Laravel APIの使い方メモ

Posted at

はじめに

前回、LaravelのフレームワークとRestAPIについてすこしお話しました。
今回は、自分が初めて使ったフレームワークの使い方が間違っていたためそのときの記事を書いていきたいと思います。
この記事は、あくまでも自分の開発では

前回の記事に、ざっくりとしたMVCのことを少し書いているので、もしよろしければこちらもご参考ください
https://qiita.com/Yami_37/items/49cda10828a23d08dfaa

APIの使い方

まず、私がAPIで使うために、はじめに考えていた間違ったMVCの認識ですが
→MVCなのだから、Model、View、Controller、ひとつずつ存在し
 ControllerでViewとAPIのデータ、両方returnしてあげる
ものだと思っていました。がControllerではviewとデータの両方の値を基本返しません。

自分はAPIController、APIModelを作らず、黄色のControllerで

return view ( '/hello.blade.php/' ,compact('data'));

と記述し、viewとデータ両方を返していました。

下の図で触れていますが、イメージとしましては、黄色のcontrollerではviewのみを返してあげます。
 →APIController(赤)でreturnするものはあくまでも「データ」です。

スクリーンショット 2020-08-13 14.40.33.png

そのために、API用のControllerとModelを作成する必要があります。
View でAPIControllerのindexを使いたい場合の流れとしては

  1. routesのwebでRoute::get('URL', 'Controller@index')にし、あくまでも、ただの「controller(黄色)」でAPIを呼び出します。
  2. Model(緑)で 「file_get_contents」か「curl」などを使いAPIControllerを実行します
  3. APIから帰ってくるデータはあくまでもJsonデータなどにし、純粋にPHPデータ使用したい場合も、Modelでデータ変換をします

ModelでAPIを叩くときは以下のような形で実装をしました。
file_get_contentsでgetする場合

public function getApiController(){
      $url = //任意のAPIURL
       $get_api_index = file_get_contents($url);
       // jsondataをPHPのデータに変換
       $get_api_index = json_decode($get_api_index, true);
       $data = $get_api_index["//受け取りたいデータ"];
       return $data;
   }

curlでputする場合は

public function putApiController(Request $request){
        $url = //任意のAPIURL
        $curl = curl_init($url);
        
        $data = $request->toArray(); //配列にしたい場合
 
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); // ※
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // ※
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
         
        $data = json_decode($response);// 配列からオブジェクトに変換
        return $data;
    }

※余談 $response_code = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
エラーが発生したかどうかを確認できる(正常なときは200がかえってくるはず)

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