HTTP 클라이언트
CI4의 CURLRequest를 사용하여 외부 API를 호출하는 방법을 알아봅니다.
GET 단건 조회
jsonplaceholder.typicode.com/posts/1에 GET 요청을 보냅니다.
POST JSON 전송
JSON 바디를 포함한 POST 요청을
jsonplaceholder.typicode.com/posts에 전송합니다.
쿼리 파라미터로 목록 조회
query 옵션으로 URL 쿼리 파라미터를 전달합니다. ?_limit=5
1
기본 사용법
// 서비스로 인스턴스 생성
$client = \Config\Services::curlrequest();
// GET 요청
$response = $client->get('https://api.example.com/posts/1');
$data = json_decode($response->getBody(), true);
$status = $response->getStatusCode(); // 200
// 헤더와 함께 요청
$response = $client->get('https://api.example.com/data', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
],
]);
2
POST / JSON 전송
// JSON 바디 전송
$response = $client->post('https://api.example.com/posts', [
'json' => [
'title' => '제목',
'body' => '본문',
'userId' => 1,
],
]);
// 폼 데이터 전송
$response = $client->post('https://api.example.com/form', [
'form_params' => [
'field1' => 'value1',
'field2' => 'value2',
],
]);
3
쿼리 파라미터 & 에러 처리
// 쿼리 파라미터 전달
$response = $client->get('https://api.example.com/posts', [
'query' => ['_limit' => 5, 'userId' => 1],
// → /posts?_limit=5&userId=1
]);
// 에러 처리
use CodeIgniter\HTTP\Exceptions\HTTPException;
try {
$response = $client->get('https://api.example.com/data', [
'timeout' => 5, // 5초 타임아웃
'http_errors' => false, // 4xx/5xx도 예외 대신 응답으로 받기
]);
if ($response->getStatusCode() >= 400) {
// 에러 응답 처리
}
} catch (HTTPException $e) {
log_message('error', $e->getMessage());
}