CodePráticov3.3.0
PHP

Como consumir uma API REST com PHP e cURL

Faça requisições GET em APIs REST usando cURL, configure timeout, leia o status HTTP e trate JSON com segurança.

Requisição GET

$ch = curl_init('https://api.exemplo.com/clientes');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json'
    ],
]);

$resposta = curl_exec($ch);

if ($resposta === false) {
    throw new RuntimeException(curl_error($ch));
}

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

Verifique o status HTTP

if ($status < 200 || $status >= 300) {
    throw new RuntimeException(
        'API retornou HTTP ' . $status
    );
}

Converter a resposta

$dados = json_decode(
    $resposta,
    true,
    512,
    JSON_THROW_ON_ERROR
);

Cuidados em produção

  • Defina timeout de conexão e resposta.
  • Não grave tokens diretamente no código-fonte.
  • Trate respostas 4xx e 5xx.
  • Registre erros suficientes para diagnóstico, sem expor dados sensíveis.