PHP 原生开发 JSON API:统一响应、参数读取和路由示例 [复制链接]

一级用户组

下面是一份不依赖框架的 PHP JSON API 示例,复制为 api.php 后即可运行。适合做小型接口、后台工具接口或快速原型。

<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

function json_response(int $code, string $message, $data = null, int $httpStatus = 200): void
{
    http_response_code($httpStatus);
    echo json_encode([
        'code' => $code,
        'message' => $message,
        'data' => $data,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function json_input(): array
{
    $raw = file_get_contents('php://input');
    if ($raw === '' || $raw === false) {
        return [];
    }

    $data = json_decode($raw, true);
    if (!is_array($data)) {
        json_response(400, '请求 JSON 格式错误', null, 400);
    }

    return $data;
}

function require_field(array $data, string $field): string
{
    $value = trim((string)($data[$field] ?? ''));
    if ($value === '') {
        json_response(422, "字段 {$field} 不能为空", null, 422);
    }
    return $value;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);

if ($method === 'GET' && $path === '/api/health') {
    json_response(0, 'ok', [
        'service' => 'php-json-api',
        'time' => date('Y-m-d H:i:s'),
    ]);
}

if ($method === 'POST' && $path === '/api/messages') {
    $input = json_input();
    $title = require_field($input, 'title');
    $content = require_field($input, 'content');

    json_response(0, '创建成功', [
        'id' => time(),
        'title' => $title,
        'content' => $content,
    ], 201);
}

json_response(404, '接口不存在', null, 404);

运行方式:

# 启动本地服务
php -S 127.0.0.1:8000 api.php

# 健康检查
curl http://127.0.0.1:8000/api/health

# 创建消息
curl -X POST http://127.0.0.1:8000/api/messages   -H 'Content-Type: application/json'   -d '{"title":"Hello","content":"PHP API"}'
最新回复

请先登录后再回复 登录

uid:4 一级用户组
关注
我与春风皆过客,你携秋水揽星河
发帖 20
评论 0
粉丝 0
关注 0
发新帖
目录
PHP 原生开发 JSON API:统一响应、参数读取和路由示例