Hello World - REST API

知识库
知识库文档
/tech-stacks/slim/examples/Hello World - REST API.md

文档

Hello World:Slim 4 REST API

目标

创建 Slim 4 最小 REST API,展示路由、请求处理和 JSON 响应。

完整代码

1. public/index.php — 入口文件

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// 可选:添加错误中间件
$app->addErrorMiddleware(true, true, true);

// Hello 端点
$app->get('/api/hello', function (Request $request, Response $response) {
    $payload = json_encode([
        'message' => 'Hello, Vibe!',
        'framework' => 'Slim 4',
        'php_version' => PHP_VERSION,
        'timestamp' => date('c'),
    ], JSON_PRETTY_PRINT);

    $response->getBody()->write($payload);
    return $response->withHeader('Content-Type', 'application/json');
});

// 带参数端点
$app->get('/api/hello/{name}', function (Request $request, Response $response, array $args) {
    $payload = json_encode([
        'message' => "Hello, {$args['name']}!",
        'powered_by' => 'Slim Framework',
    ]);

    $response->getBody()->write($payload);
    return $response->withHeader('Content-Type', 'application/json');
});

// POST 示例
$app->post('/api/echo', function (Request $request, Response $response) {
    $body = json_decode($request->getBody()->__toString(), true);

    $payload = json_encode([
        'you_sent' => $body,
        'received_at' => date('c'),
    ]);

    $response->getBody()->write($payload);
    return $response->withHeader('Content-Type', 'application/json');
});

$app->run();

运行步骤

php -S localhost:8080 -t public/

预期输出

curl http://localhost:8080/api/hello
# {"message":"Hello, Vibe!","framework":"Slim 4","php_version":"8.2.0","timestamp":"..."}

curl http://localhost:8080/api/hello/Vibe
# {"message":"Hello, Vibe!","powered_by":"Slim Framework"}

curl -X POST http://localhost:8080/api/echo \
  -H "Content-Type: application/json" \
  -d '{"foo":"bar"}'
# {"you_sent":{"foo":"bar"},"received_at":"2024-01-01T00:00:00+00:00"}

信息

路径
/tech-stacks/slim/examples/Hello World - REST API.md
更新时间
2026/5/31