Codeigniter4ではAPIのクラスが存在し手軽にAPIの開発ができるようになっている。
CodeIgniter\API\ResponseTrait をインポートする事で様々なCI4が用意しているメソッドを利用可能。
エラー用メソッドも多数用意されている。
【例】
/app/Controllers/Users.php
<?php namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
class Users extends \CodeIgniter\Controller {
	use ResponseTrait;
	public function index(){
		return $this->respond(array("aaa"=>"bbb"));
	}
	public function show($id=null) {
		if(empty($id)) return $this->failValidationErrors();
		if($id==3) {
			return $this->failNotFound();
		} else {
			return $this->respond(array("Users" =>
					array(
						"id" => 1, "name" => "hogehoge",
						"id" => 2, "name" => "fugaguga"
					))
			);
		}
	}
}
?>
■結果
- Request
http://***/users/
- Response
{
    "aaa": "bbb"
}
- Request

 http://***/users/show/1
- Response
{
    "Users": {
        "id": 2,
        "name": "fugaguga"
    }
}
- Request

 http://***/users/show/3
- Response
Header HTTP 404 not found
Body
{
    "status": 404,
    "error": 404,
    "messages": {
        "error": "Not Found"
    }
}
      
コメント