PHP talks to POST https://api.trendsapi.ai/api with cURL. Auth is a Bearer header. The envelope field body is a JSON string and must be parsed a second time. json_decode on the raw response only builds the envelope. A second json_decode on body builds the board or the series. getenv should fail closed if the token is empty. Guzzle is optional when the app already has it. Docs: the API reference. Caps: pricing. Reddit boards: the Reddit guide.
curl_setopt POSTFIELDS
$key = getenv("TRENDSAPI_API_KEY");
if ($key === false || $key === "") {
throw new RuntimeException("TRENDSAPI_API_KEY missing");
}
$payload = json_encode([
"mode" => "get_top_trends",
"type" => "Reddit Hot Posts",
"limit" => 10,
]);
$ch = curl_init("https://api.trendsapi.ai/api");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer {$key}",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
]);
$raw = curl_exec($ch);
if ($raw === false) {
throw new RuntimeException(curl_error($ch));
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code >= 300) {
throw new RuntimeException("http {$code}");
}
Reddit Hot Posts is a labeled sample. No keyword on that mode.
json_decode the body string
$outer = json_decode($raw, true);
$inner = json_decode($outer["body"], true);
true yields arrays. Objects work if the next layer expects them. Skipping the second decode leaves a quoted JSON string. CURLOPT_CONNECTTIMEOUT is the TCP wait. CURLOPT_TIMEOUT is the whole request. Set both so a hung DNS lookup cannot hold an FPM worker.
getenv and putenv
putenv in a front controller is process-wide. Prefer the host's secret mechanism (FPM env, .env loaded once). Do not var_dump($key).
Guzzle is optional
// $client->post('https://api.trendsapi.ai/api', ['json' => $payload, 'headers' => [...]]);
Same envelope. Same second json_decode. A 429 is this product's burst or plan signal. Read pricing. Do not retry a 401. That is a missing or revoked key, not a transient board miss. The product MCP server at https://api.trendsapi.ai/mcp is not a PHP package.