简体   繁体   中英

Symfony 4 implement REST API

I'm implementing a simple REST API in my Symfony 4 project. When I test the getArticle() function with Postman this is the error:

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

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.

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. For details why and what it does read the FOSRest documentation here .

fos_rest:
  view:
    view_response_listener:  true

Also add this to your fos_rest.yaml to select your output format -> here 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.

/**
 * 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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