RESTful API
CI4로 JSON 기반의 RESTful API를 개발하는 패턴을 알아봅니다.
1
JSON 응답 기본
class Api extends BaseController
{
public function users(): ResponseInterface
{
$users = [/* ... */];
return $this->response
->setStatusCode(200)
->setJSON([
'success' => true,
'count' => count($users),
'data' => $users,
]);
}
}
2
HTTP 상태 코드 처리
// 200 OK — 조회 성공
return $this->response->setStatusCode(200)->setJSON(['data' => $item]);
// 201 Created — 생성 성공
return $this->response->setStatusCode(201)->setJSON(['message' => '생성 완료', 'data' => $new]);
// 404 Not Found — 리소스 없음
return $this->response->setStatusCode(404)->setJSON(['error' => '존재하지 않습니다.']);
// 422 Unprocessable Entity — 유효성 검사 실패
return $this->response->setStatusCode(422)->setJSON(['errors' => $this->validator->getErrors()]);
// 401 Unauthorized — 인증 필요
return $this->response->setStatusCode(401)->setJSON(['error' => '토큰이 필요합니다.']);
3
POST API 라이브 테스트
JSON Body로 POST 전송
응답
// 버튼을 클릭하면 결과가 여기에 표시됩니다
컨트롤러
public function createUser(): ResponseInterface
{
$json = $this->request->getJSON(true); // JSON body 파싱
$rules = ['name' => 'required', 'email' => 'required|valid_email'];
if (! $this->validate($rules)) {
return $this->response->setStatusCode(422)
->setJSON(['errors' => $this->validator->getErrors()]);
}
return $this->response->setStatusCode(201)
->setJSON(['success' => true, 'data' => $json]);
}