[英]Multiple root route for FOSRestBundle
I'm using the FOSRestBundle and I can't find how to have two different endpoint, one for the template rendering (html/twig, /app
for example) and another one for the serialization (json, /api
for example). 我正在使用FOSRestBundle,我找不到如何使用两个不同的端点,一个端点用于模板渲染(例如html / twig,
/app
),另一个端点用于序列化(例如json, /api
)。 Is it possible ? 可能吗 ? The documentation for FOSRestBundle Automatic Route generation , does not indicate any of this.
FOSRestBundle自动路由生成的文档没有对此进行任何说明。
Using Symfony 3 and FOSRestBundle 2.x 使用Symfony 3和FOSRestBundle 2.x
You can configure this via format listeners in your app/config.yml. 您可以通过app / config.yml中的格式侦听器进行配置。
fos_rest:
format_listener:
rules:
- { path: '^/api', priorities: [json], fallback_format: json, prefer_extension: false }
- { path: '^/', priorities: ['text/html', '*/*'], fallback_format: html, prefer_extension: false }
param_fetcher_listener: force
view:
view_response_listener: force
formats:
json: true
html: true
About the routing part, here's an example of one controller with two actions, one for each type of response (annotations): 关于路由部分,这是一个具有两个动作的控制器的示例,每个动作对应一种响应(注释):
namespace RVW\AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations\Route;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class BrandController extends FOSRestController
{
/**
* @param Request $request
* @View(statusCode=Response::HTTP_OK)
* @Route("/brands", name="brands")
* @Method({"GET"})
*
* @return View
*/
public function brandsAction(Request $request): View
{
return $this->container->get('doctrine')->getRepository('AppBundle:Brand')->findAll();
}
/**
* @Route("/", name="index")
*
* @return Response
*/
public function indexAction(Request $request): Response
{
return $this->render('@App/index.html.twig', [
'data' => $data,
]);
}
}
Cheers, 干杯,
Simply specify a prefix
in your routing configuration. 只需在路由配置中指定
prefix
。
If you're using YAML, you can change your routing.yml
file: 如果您使用的是YAML,则可以更改
routing.yml
文件:
app:
resource: '@AppBundle/Controller/'
type: annotation
prefix: /app
api:
type: rest
resource: AppBundle\Controller\RestController
prefix: /api
Now your normal routes start with /app
and your REST routes start with /api
现在,您的常规路由以
/app
开头,而REST路由以/api
开头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.