In PHP REST APIs, how do I expose a REST API?

In this example, we will demonstrate how to expose a REST API using PHP. REST (Representational State Transfer) APIs are widely used for communication between clients and servers over the HTTP protocol.

Example of a Simple REST API in PHP

<?php // Set header to allow JSON output header('Content-Type: application/json'); // Dummy data for demonstration $data = [ ['id' => 1, 'name' => 'John Doe'], ['id' => 2, 'name' => 'Jane Smith'], ]; // Get the HTTP method $method = $_SERVER['REQUEST_METHOD']; // Handle GET request to fetch data if ($method === 'GET') { echo json_encode($data); } ?>

This basic code sets up a simple REST API that responds to GET requests by returning a JSON array of users. You can expand this foundation into a more comprehensive API.


PHP REST API expose REST API JSON response HTTP protocol web services