How to specify default format for FOS\RestBundle to json?

本小妞迷上赌 提交于 2019-12-19 05:42:52

问题


My corresponding configuration is

fos_rest:
    view:
        view_response_listener: force

sensio_framework_extra:
    view:
        annotations: false

and it really annoys to specify the route as

@Route("/jobs", defaults={ "_format" = "json" })

every time.

So is it possible to specify it somewhere to be assumed by default?

PS:

If I remove defaults={ "_format" = "json" } and call the /jobs endpoint I'm getting an exception

Unable to find template "APIBundle:Jobs:post.html.twig".

PPS:

routing_loader:
    default_format: json

won't work because it's only used for automatic routes generation.


回答1:


The final answer is much easier and is irrelevant to FOS\RestBundle:

api:
    resource: "@APIBundle/Controller/"
    type:     annotation
    defaults: {_format: json} # <<<<<<<
    prefix:   /api/



回答2:


You may specify a default_format that the routing loader will use for the _format parameter if none is specified.

# app/config/config.yml
fos_rest:
    routing_loader:
        default_format: json

By default, routes are generated with {_format} string. If you want to get clean urls (/jobs instead /jobs.{_format}) then all you have to do is add some configuration:

# app/config/config.yml
fos_rest:
    routing_loader:
        include_format:       false

Have a look at the FOSRestBundle documentation for more informations.




回答3:


I couldn't test this solution myself but following the documentation it seems that you can use a default format by giving rules on path

config.yml

fos_rest:
    format_listener:
        rules:
            # setting fallback_format to json means that instead of considering
            # the next rule in case of a priority mismatch, json will be used
            -
                path: '^/'
                host: 'api.%domain%'
                priorities: ['json', 'xml']
                fallback_format: json
                prefer_extension: false

With such, a request made with Accept-headers containing

text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json

Will result in a json Request format



来源:https://stackoverflow.com/questions/19395055/how-to-specify-default-format-for-fos-restbundle-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!