4

REST API 呼び出しが 1 つあるとします。

/api/message/list

HTTP Accept Header に応じて異なるレスポンス形式を持ちたい。

curl コマンドから JSON または XML を要求すると、完璧に機能します。しかし、ブラウザーからロードすると、小枝テンプレートをレンダリングしようとしますが、それは望ましくありません。HTML ではなく XML コンテンツを返したい。このアプローチでは、ブラウザー出力用の twig ファイルを作成する必要はありません。

小枝を作成する必要なく、ブラウザーに API 出力を持たせることが実用的であるため、これを行いたいと考えています。

構成ファイルに何か不足していますか? それとも、これは現在デフォルトでサポートされていないのでしょうか?

これを使ってみましたがうまくいきません。

fos_rest:
    body_listener:
        decoders:
            html: fos_rest.decoder.xml
            ...

config.yml の完全な FOSRest 構成:

fos_rest:
    param_fetcher_listener: true
    body_listener:
      decoders:
        json: fos_rest.decoder.json
        xml: fos_rest.decoder.xml
        html: fos_rest.decoder.xml
    format_listener:
      default_priorities: [html, xml, json]
      fallback_format: xml
    view:
        view_response_listener: force
        formats:
            json: true
            xml: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: php

sensio_framework_extra:
    view:    { annotations: false }
    router:  { annotations: true }

コントローラーのリスト アクションは、メッセージの配列だけを返します。

<?php

use FOS\RestBundle\Controller\Annotations as Rest;

class MessageController extends Controller {

    /**
     * @Rest\View()
     */
    public function listAction() {
        $messages = //get the messages
        return $messages;
    }

    ...
}
?>

ありがとう!

4

0 に答える 0