Swagger Codegenが生成するPHPクライアントを使う機会があったので、使い方を記事に残しておきます。
Swagger Codegenが生成するファイル
Swagger CodegenでPHPテンプレートを指定すると、以下のファイル群が生成されます。
- SwaggerClient-php/
Petstoreの例が参考になります。 swagger-codegen/samples/client/petstore/php at master · swagger-api/swagger-codegen · GitHub から参照できます。
APIクライアントの使い方
APIクライアントのインスタンスを生成し、メソッドを実行します。
require_once(__DIR__ . '/SwaggerClient-php/autoload.php');
// APIクライアントの生成
$pet_api = new Swagger\Client\Api\PetApi();
// APIの実行
$the_pet = $pet_api->getPetById(1);
この例ではID=1のPetモデルを取得しています。getPetById メソッドはAPIクライアントクラス(PetApi.php)で定義されています。
/**
* Operation getPetById
*
* Find pet by ID
*
* @param int $pet_id ID of pet to return (required)
* @throws \Swagger\Client\ApiException on non-2xx response
* @return \Swagger\Client\Model\Pet
*/
public function getPetById($pet_id)
また、getPetById メソッドが返すモデルはモデルクラス(Pet.php)で定義されています。
/** * Pet Class Doc Comment * * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class Pet implements ArrayAccess
モデルクラスはArrayAccessを実装しているため、配列としてアクセスできるように設計されています。また、GetterとSetterでもアクセスできるようになっています。
$the_pet->getName(); $the_pet['name']; $the_pet->setName('foo'); $the_pet['name'] = 'foo';
例外処理
APIが200番台以外のステータスコードを返した場合は例外が発生します。ステータスコードやレスポンスは例外オブジェクトから取得できます。
try {
$the_pet = $pet_api->getPetById(1);
} catch (Swagger\Client\ApiException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
echo 'HTTP response headers: ', $e->getResponseHeaders(), "\n";
echo 'HTTP response body: ', $e->getResponseBody(), "\n";
echo 'HTTP status code: ', $e->getCode(), "\n";
}
APIクライアントの設定とカスタマイズ
APIクライアントの getConfig メソッドでヘッダやOAuthなどを設定できるようになっています。
$pet_api->getApiClient()->getConfig();
詳しくは swagger-codegen/Configuration.php at master · swagger-api/swagger-codegen · GitHub が参考になります。
今のところ、APIクライアントにはインターセプタの仕組みは用意されていないようです。共通処理を入れたい場合は ApiClient クラスを継承した独自クラスを定義し、APIクライアントのコンストラクタに渡すとよいでしょう。
class MyApiClient extends Swagger\Client\ApiClient
{
public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null)
{
// TODO: 事前処理
$response = parent::callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType, $endpointPath);
// TODO: 事後処理
return $response;
}
}
$pet_api = new Swagger\Client\Api\PetApi(new MyApiClient());
依存関係の管理
composer.jsonとautoload.phpが生成されるので、Composerで依存関係を管理することも可能です。ここで力尽きたので詳細は割愛します。