CI4의 CURLRequest를 사용하여 외부 API를 호출하는 방법을 알아봅니다.
jsonplaceholder.typicode.com/posts/1
jsonplaceholder.typicode.com/posts
query
?_limit=5
// 서비스로 인스턴스 생성 $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', ], ]);
// 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', ], ]);
// 쿼리 파라미터 전달 $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()); }