はじめに
皆様はAPIの打鍵をする際にどんなツールを使用しているでしょうか?
大半の方はPostmanを使用していると思いますが
私の劇推しするJetBrains社IDEを使用してAPIを打鍵したいと思います
JetBrains社IDE【統合開発環境】の良いところ
今回の主題となるHTTPクライアント機能を紹介したいと思います
環境
環境は以下の通り(今回はPhpStormを使用します)
PHP:8.0.6
Laravel Framework:8.44.0
PhpStorm:PhpStorm 2024.3.1.1
OS:Windows10
前提条件
今回はMySQLにあるnamesテーブルから
Laravelで作成したnamesテーブルから1レコードを取得するAPIに対してAPI打鍵を行います。
(controllerにビジネスロジックを実装しているアンチパターンなのはご了承下さい...)
app/Http/Controllers/NamesController.php
<?php
namespace App\Http\Controllers;
use App\Models\names;
use http\Env\Response;
use Illuminate\Http\Request;
class NamesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
return response()->json(
[
'message' => 'Name get successfully',
'data' => names::get(['id', 'name'])
],
\Illuminate\Http\Response::HTTP_OK,
[
'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => 'GET',
'Access-Control-Allow-Headers' => 'Content-Type'
],
JSON_UNESCAPED_UNICODE
);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param $id int
* @return \Illuminate\Http\JsonResponse
*/
public function show($id)
{
return response()->json(
[
'message' => 'Name get successfully',
'data' => names::find($id, ['id', 'name'])
],
\Illuminate\Http\Response::HTTP_OK,
[
'Access-Control-Allow-Origin' => 'http://localhost:8080',
'Access-Control-Allow-Methods' => 'GET',
'Access-Control-Allow-Headers' => 'Content-Type'
],
JSON_UNESCAPED_UNICODE);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\names $names
* @return \Illuminate\Http\Response
*/
public function edit(names $names)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\names $names
* @return \Illuminate\Http\Response
*/
public function update(Request $request, names $names)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\names $names
* @return \Illuminate\Http\Response
*/
public function destroy(names $names)
{
//
}
}
API打鍵の仕方
name.http
GET http://127.0.0.1:8000/api/names/1
- atrisanコマンドを実行してlocalhostのAPIを起動します(今回は「▷(artisanの実行)」(①)と予めPhpStormの中でコマンド定義済です。この手順についても追々記事にしたいと思います。)
- localhostでAPIが起動出来ました
- APIを実行してみたいと思います。行番号の隣の「▷」(①)を押下してみましょう。
- APIが実行されました
レスポンスとしては以下2つの条件を満たしたため、API打鍵成功です。
- namesテーブルのid = 1である「あああ」さんの情報がJSONで取得出来た
- ステータスとして200(OK)が返って来た
さいごに
こんな感じでPostmanを使用せずにJetBrains社IDE【統合開発環境】だけでAPIの打鍵が出来ました
今回はGETするだけの簡単なAPIでしたが
POSTしたりトークン使用する様な複雑なAPIについてもJetBrains社IDE【統合開発環境】を
使用する事によって難なくAPIの打鍵が出来てしまいます
より高度な使い方については気が向いたら記事を作成するかも知れません