簡體   English   中英

Symfony 4實現REST API

[英]Symfony 4 implement REST API

我在Symfony 4項目中實現了一個簡單的REST API。 當我用Postman測試getArticle()函數時,這是錯誤:

控制器必須返回響應(給定的Object(FOS \\ RestBundle \\ View \\ View))。

使用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文檔。

fos_rest:
  view:
    view_response_listener:  true

還要將此添加到您的fos_rest.yaml中以選擇輸出格式->此處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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM