symfony 6.4.48 中可纯框架快速搭建 api:1. 用 make:controller 创建控制器,调用 $this->json() 返回 json;2. 通过 request->toarray() 解析 json 请求体,结合 validatorinterface 验证;3. 注解配置路由,封装 apiresponse() 统一响应格式;4. 安装配置 nelmio/cors-bundle 支持跨域。

在 Symfony 6.4.48 中搭建 API 应用并添加接口返回,核心是使用控制器返回 JSON 响应,并配合序列化、验证和路由配置。不需要额外安装 API 平台(除非你明确需要),纯 Symfony 就能快速提供 RESTful 接口。
1. 创建控制器并返回 JSON
Symfony 默认支持 JsonResponse,推荐用它直接返回结构化数据:
- 运行命令生成控制器:
php bin/console make:controller ApiController - 在
src/Controller/ApiController.php中修改index方法:
use Symfony\Component\HttpFoundation\JsonResponse;
public function index(): JsonResponse
{
return $this->json([
'status' => 'success',
'data' => ['message' => 'Hello from Symfony API'],
'timestamp' => new \DateTimeImmutable(),
]);
}
注意:$this->json() 是 Symfony 提供的快捷方法,自动设置 Content-Type: application/json 并处理对象序列化(如 DateTimeImmutable)。
2. 处理请求参数与验证
API 接口常需接收查询参数、JSON 请求体或表单数据。以接收 POST JSON 数据为例:
- 在控制器中注入
Request对象 - 用
$request->toArray()解析 JSON 请求体(需确保 Content-Type 是application/json) - 结合
Validator组件做字段校验(需已启用验证,Symfony 默认开启)
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;
public function create(Request $request, ValidatorInterface $validator): JsonResponse
{
$data = $request->toArray();
$constraints = new Assert\Collection([
'name' => [new Assert\Required(), new Assert\Length(['min' => 2])],
'email' => [new Assert\Required(), new Assert\Email()],
]);
$violations = $validator->validate($data, $constraints);
if (count($violations) > 0) {
return $this->json([
'error' => 'Validation failed',
'details' => (string) $violations,
], 400);
}
// 保存逻辑...
return $this->json(['id' => 123, 'name' => $data['name']], 201);
}
3. 配置路由与格式化响应
确保路由支持 JSON 格式,推荐显式指定 format 或通过 Accept 头协商:
- 在
config/routes.yaml中为控制器启用注解路由(若未禁用) - 或直接在控制器方法上加注解:
@Route("/api/users", name="api_users", methods: ["GET"]) - 如需统一响应结构(如包裹 data/status/code),可创建一个简单响应类或复用
ApiPlatform\Core\Util\LegacyResponseHelper(不推荐强耦合) - 更轻量做法:写一个私有方法封装标准返回格式
private function apiResponse($data = [], int $status = 200, string $message = 'OK'): JsonResponse
{
return $this->json([
'success' => $status $message,
'data' => $data,
'timestamp' => date('c'),
], $status);
}
// 使用示例
return $this->apiResponse(['user' => $user], 200);
4. 启用 CORS(前端调用必需)
若前端跨域访问,需启用 nelmio/cors-bundle:
- 安装:
composer require nelmio/cors-bundle - 配置
config/packages/nelmio_cors.yaml:
nelmio_cors:
defaults:
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
allow_headers: ['*']
expose_headers: ['Link']
max_age: 3600
paths:
'^/api/': ~
然后在 .env 设置:CORS_ALLOW_ORIGIN="https://your-frontend.com http://localhost:3000"。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











