简体   繁体   English

Symfony 4实现REST API

[英]Symfony 4 implement REST API

I'm implementing a simple REST API in my Symfony 4 project. 我在Symfony 4项目中实现了一个简单的REST API。 When I test the getArticle() function with Postman this is the error: 当我用Postman测试getArticle()函数时,这是错误:

The controller must return a response (Object(FOS\\RestBundle\\View\\View) given). 控制器必须返回响应(给定的Object(FOS \\ RestBundle \\ View \\ View))。

With a var_dump($articles) content is displayed as expected so I guess the problem could be the FOSRestBundle but I don't know other ways to do this job. 使用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);
 }
}

Define a view response listener in your config/packages/fos_rest.yaml. 在config / packages / fos_rest.yaml中定义一个视图响应侦听器。 For details why and what it does read the FOSRest documentation here . 有关原因和作用的详细信息,请在此处阅读FOSRest文档。

fos_rest:
  view:
    view_response_listener:  true

Also add this to your fos_rest.yaml to select your output format -> here json 还要将此添加到您的fos_rest.yaml中以选择输出格式->此处json

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

I've found a solution by myself returning a HttpFoundation\\Response, it might be helpful to someone. 我自己找到了返回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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM