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

In PHP microservices, exposing a REST API can be accomplished by using various PHP frameworks such as Laravel, Slim, or even plain PHP. The following example demonstrates how to create a simple REST API using plain PHP.

<?php // Enable CORS header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); // Sample data to simulate a database $data = [ ["id" => 1, "name" => "Product 1"], ["id" => 2, "name" => "Product 2"], ["id" => 3, "name" => "Product 3"] ]; // Handle the GET request if ($_SERVER['REQUEST_METHOD'] == 'GET') { echo json_encode($data); } else { http_response_code(405); // Method Not Allowed echo json_encode(["message" => "Method Not Allowed"]); } ?>

PHP microservices REST API PHP frameworks Laravel Slim CORS JSON GET requests