Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to send an HTTP request to an API

Short answer

file_get_contents() performs a simple GET request:

<?php
 
// rates.php
 
$data = json_decode(file_get_contents('https://api.example.com/rates'), true);
 
echo $data['rates']['EUR'];

A JSON POST

Use cURL to send data and headers:

<?php
 
// create-order.php
 
$curl = curl_init('https://api.example.com/orders');
 
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 5,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode(['product_id' => 42]),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
 
$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
 
if ($body === false || $status >= 400) {
    exit('Request failed');
}
 
$order = json_decode($body, true);

Do not forget the timeout

Without CURLOPT_TIMEOUT a request to a hung service keeps your page open.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.