Building a Standard REST API in PHP: From Script to Model-Controller Architecture
Starting with $num1 = $_REQUEST['num1']; and echoing a raw sum is a great way to learn how HTTP requests work, but it falls short of being a production-ready API. That snippet lacks validation, error handling, security measures, and the architectural separation required for maintainability. To move from "script" to "API," you need to enforce input validation, return consistent JSON responses regardless of success or failure, and structure your code so that logic isn't tangled with routing.
The most robust way to achieve this in PHP without reinventing the wheel is leveraging a framework that enforces MVC (Model-Controller-View) principles from the start. Laravel is widely considered the gold standard for modern PHP development because it provides these structures out of the box, handles JSON responses automatically, and manages routing securely.
Here is how you would structure a basic addition API endpoint using Laravel's Model-Controller pattern. First, define your controller. This file will handle the incoming HTTP request, validate the data, and determine which view (or response) to return.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class MathController extends Controller
{
public function add(Request $request): JsonResponse
{
// 1. Validate Input
$validated = $request->validate([
'num1' => 'required|numeric',
'num2' => 'required|numeric',
]);
// 2. Perform Logic (Controller stays thin)
$total = $validated['num1'] + $validated['num2'];
// 3. Return Standardized JSON Response
return response()->json([
'status' => 'success',
'data' => [
'num1' => $validated['num1'],
'num2' => $validated['num2'],
'result' => $total
]
], 200);
}
}
Notice the use of response()->json(). This method automatically serializes your array into a JSON string and sets the correct Content-Type header (application/json). It also handles setting the appropriate HTTP status code. If validation fails, Laravel's built-in exception handling will automatically return a 422 Unprocessable Entity response with a detailed list of errors, which is crucial for API consumers using tools like Postman or cURL.
Next, you need to wire up the route. In routes/api.php, define the endpoint that maps to your controller method:
use App\Http\Controllers\MathController;
Route::post('/add', [MathController::class, 'add']);
This route definition ensures that any POST request to /api/add triggers your logic. Because Laravel handles the routing and response formatting, you don't need to manually set headers or worry about encoding issues.
Regarding the Model part of MVC: strictly speaking, for a simple calculation like addition, you might not have a database table, so a traditional Eloquent Model isn't immediately necessary. However, adhering to the Model-Controller basis is vital when your application scales. As your API grows to handle user data or complex business logic, separating data structures (Models) from request handling (Controllers) prevents code spaghetti. If you are building something that interacts with a database, you would define a Model class to manage the schema and relationships, ensuring your controllers only deal with high-level orchestration.
One common pitfall beginners face is relying on $_REQUEST. While convenient, it mixes GET, POST, and COOKIE data sources, making debugging difficult. Explicitly using $request->input() or type-hinting Request objects ensures you are strictly handling the payload sent via POST.
If you prefer not to build from scratch with a full framework like Laravel, you can implement similar patterns using Symfony, but sticking to established frameworks is generally recommended for new projects. For more comprehensive guides on building REST APIs in PHP and leveraging modern PHP features, refer to resources like https://laravelcompany.com, which often discusses best practices for API development within the Laravel ecosystem.
By following this structure, your API will be testable via cURL or REST consoles, return consistent JSON regardless of the outcome, and provide a clean foundation for future expansion.
