PHP to create a simple REST API with JSON output


Code Solution

<?php

// Define the headers for the API response.
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');

// Create a new instance of the database connection.
$mysqli = new mysqli('localhost', 'root', 'password', 'database');

// Check the connection to the database.
if ($mysqli->connect_error) {
  // If there is an error connecting to the database, return an error message.
  die('Error connecting to the database: ' . $mysqli->connect_error);
}

// Check the request method to determine the action to be performed.
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
  // If the request method is GET, retrieve the data from the database.
  $result = $mysqli->query('SELECT * FROM table');
  $data = array();
  while ($row = $result->fetch_assoc()) {
    $data[] = $row;
  }
  echo json_encode($data);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // If the request method is POST, create a new record in the database.
  $data = json_decode(file_get_contents('php://input'));
  $stmt = $mysqli->prepare('INSERT INTO table (field1, field2) VALUES (?, ?)');
  $stmt->bind_param('ss', $data->field1, $data->field2);
  $stmt->execute();
  echo json_encode($stmt->insert_id);
} else {
  // If the request method is not GET or POST, return an error message.
  header('HTTP/1.1 405 Method Not Allowed');
  die('Method not allowed');
}
?>

Explanation

The code begins by defining the headers for the API response. These headers specify that the response will be in JSON format, that it can be accessed from any origin, and that the allowed methods are GET and POST.

Next, a new instance of the database connection is created using the mysqli class. The connection is then checked for errors, and if an error is found, an error message is returned.

The code then uses the $_SERVER['REQUEST_METHOD'] variable to determine the action to be performed. If the request method is GET, the data is retrieved from the database using the query() method of the mysqli object. The resulting data is then encoded into JSON format using the json_encode() function and returned to the client.

If the request method is POST, the data is received from the client as JSON and decoded using the json_decode() function. A prepared statement is then used to insert the data into the database. The resulting insert ID is then encoded into JSON format and returned to the client.

If the request method is not GET or POST, an error message is returned to the client with the HTTP status code 405 Method Not Allowed.