Building RESTful APIs with ThinkPHP and Resolving Unexpected 500 Errors
When developing RESTful APIs using the ThinkPHP framework, adhering to naming conventions and understanding how to handle different types of HTTP request payloads is essential. Missteps in these areas often lead to unexpected behavior or server errors.
For JSON-based APIs, especially in a decoupled frontend-backend architecture, handling request bodies correctly is crucial. Unlike traditional form submissions that populate $_POST, AJAX requests sending raw JSON must be read via:
$rawInput = file_get_contents('php://input');
$inputData = json_decode($rawInput, true);
To standardize API responses, a base controller can encapsulate common functionality such as formatting JSON output, extracting query parameters, and parsing request bodies:
<?php
namespace app\common\controller;
use think\Controller;
use think\Response;
class ApiBaseController extends Controller
{
protected function sendJson($code = 200, $message = 'success', $payload = [], $httpStatus = 200): Response
{
return json([
'code' => $code,
'msg' => $message,
'data' => $payload
], $httpStatus);
}
protected function getRequestBody(): ?object
{
$content = file_get_contents('php://input');
return !empty($content) ? json_decode($content) : null;
}
protected function getBodyParam(string $key)
{
$body = $this->getRequestBody();
return $body && isset($body->$key) ? $body->$key : null;
}
protected function getQueryParam(string $key)
{
return isset($_GET[$key]) ? $_GET[$key] : null;
}
}
This approach promotes cleaner, more maintainible code by separating concerns—such as input parsing, bussiness logic, and response formatting—into distinct layers.
A particularly elusive issue during development was receeiving HTTP 500 errors despite seemingly correct logic and valid responses. After inspecting server logs, the root cause was traced to insufficient write permissions on the public/runtime directory. ThinkPHP requires this directory to store cache, logs, and temporary files. Ensuring the web server (e.g., Apache or Nginx) has write access to runtime resolves the silent failure that manifests as a 500 Internal Server Error.