Junior — Middle
How to send and save data via REST API?
sobes.tech AI
Answer from AI
To send and save data via REST API in PHP, you can use the following approach:
-
Sending data (client-side):
- Use
curlor libraries like Guzzle to send HTTP requests. - Send data in JSON format or as form-data.
- Use
-
Processing the request on the server (server-side):
- Retrieve incoming data from
php://inputor through superglobal arrays ($_POST,$_GET). - Parse JSON if the data is in that format.
- Validate and check the data.
- Save the data to a database or a file.
- Retrieve incoming data from
Example of sending a POST request with JSON via curl in PHP:
$data = ['name' => 'Ivan', 'age' => 30];
$jsonData = json_encode($data);
$ch = curl_init('https://example.com/api/save');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Example of processing the request on the server:
// Get JSON from request body
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if ($data && isset($data['name'])) {
// Logic to save data, e.g., to a database
// ...
echo json_encode(['status' => 'success']);
} else {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
}