Symfony 4 实现 REST API

Symfony 4 implement REST API

我正在我的 Symfony 4 项目中实现一个简单的 REST API。当我用 Postman 测试 getArticle() 函数时,这是错误:

The controller must return a response (Object(FOS\RestBundle\View\View) given).

var_dump($articles) 内容按预期显示,所以我猜问题可能出在 FOSRestBundle,但我不知道其他方法可以完成这项工作。

class ArticleController extends FOSRestController
{

/**
 * Retrieves an Article resource
 * @Rest\Get("/articles/{id}")
 */
public function getArticle(int $articleId): View
 {
    $em = $this->getDoctrine()->getManager();
    $article = $em->getRepository(Article::class)->findBy(array('id' => $articleId));

    // In case our GET was a success we need to return a 200 HTTP OK response with the request object
    return View::create($article, Response::HTTP_OK);
 }
}

在您的 config/packages/fos_rest.yaml 中定义一个视图响应侦听器。有关详细信息,请阅读 FOSRest 文档 here.

fos_rest:
  view:
    view_response_listener:  true

同时将此添加到您的 fos_rest.yaml 到 select 您的输出格式 -> 此处 json

fos_rest:
  [...] 
  format_listener:
    rules:
      - { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ json ] }

我自己找到了一个解决方案,返回一个HttpFoundation\Response,它可能对某人有帮助。

/**
 * Lists all Articles.
 * @FOSRest\Get("/articles")
 */
public function getArticles(Request $request): Response
{
    $em = $this->getDoctrine()->getManager();
    $articles = $em->getRepository(Article::class)->findAll();

    return new Response($this->json($articles), Response::HTTP_OK);
}