简体   繁体   中英

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). Is it possible ? The documentation for FOSRestBundle Automatic Route generation , does not indicate any of this.

Using Symfony 3 and FOSRestBundle 2.x

You can configure this via format listeners in your 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.

If you're using YAML, you can change your routing.yml file:

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

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