16

Can someone clearly explain how routes are supposed to be configured for REST requests using FOSRest? Every tutorial seems to do it differently.

My Controller:

<?php
namespace Data\APIBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DatasetController extends Controller{

 protected function postDatasetAction(Request $request){
  //Query here
}

The URL should look something like this: Symfony/web/app_dev.php/api/dataset. So I thought the routes should be something like...

app/config/routes.yml

data_api:
  resource: "@DataAPIBundle/Resources/config/routing.yml"
  prefix: /api
  type: rest

And....

Data/APIBundle/Resources/config/routing.yml

data_query:
  type: rest
  pattern:  /dataset
  defaults: {_controller: DataAPIBundle:Dataset:datasetAction, _format: json }
  requirements:
     _method: POST
user2142111
  • 161
  • 1
  • 1
  • 4
  • This question isn't clear, at least to me (maybe because I don't know FOSRestBundle) but, what do you whant to know? This seem pretty clear: you have a route under `yourWebSiteDomain/api/dataset` that you can access only via post method and format of the request should be json. – DonCallisto Mar 07 '13 at 07:55
  • 2
    Seems that the user is asking for a canonical tutorial on how to build routes in FOSRestBundle. As he mentioned, every tutorial on FOSRestBundle handles the routes differently. Really there needs to be a single resource (i.e. - the project docs) that defines clearly the possible varying configurations, as currently it's not obvious what all is possible. – Jon L. Apr 07 '13 at 05:32

2 Answers2

18

Please follow the next URL to read the official documentation: http://symfony.com/doc/master/bundles/FOSRestBundle/index.html

To start with this bundle, I would suggest following the single restful controller documentation: http://symfony.com/doc/master/bundles/FOSRestBundle/5-automatic-route-generation_single-restful-controller.html

You will also find clear examples (https://github.com/liip/LiipHelloBundle) about what this bundle can offer.


Few things from the snippets you have posted drew my attention:

The visibility of your controller method is protected whereas it should be public (http://symfony.com/doc/current/book/controller.html)

public function postDatasetAction(Request $request) {
     // your code
}

The "routing.yml" file created to configure your route shall contain the name of the aforementioned controller method (postDatasetAction instead of DatasetAction):

# routing.yml
data_query:
    type: rest
    pattern:  /dataset
    defaults: {_controller: DataAPIBundle:Dataset:postDatasetAction, _format: json }
    requirements:
        _method: POST

Please find below an example to setup a route like :

get_items GET ANY ANY /items.{json}

# config.yml
fos_rest:
    allowed_methods_listener: true

    format_listener:
        default_priorities: ['json', html, '*/*']
        fallback_format: json
        prefer_extension: true

    param_fetcher_listener: true

    routing_loader:
        default_format: json

    view:
        formats:
            json: true
        mime_types:
            json: ['application/json', 'application/x-json']
        force_redirects:
            html: true
        view_response_listener: force

# routing.yml
categories:
    type:     rest
    resource: Acme\DemoBundle\Controller\ItemController

<?php

namespace Acme\DemoBundle\Controller

use FOS\RestBundle\Request\ParamFetcher;
use FOS\RestBundle\Controller\Annotations as Rest;

class ItemController 
{
    /**
     * Get items by constraints
     *
     * @Rest\QueryParam(name="id", array=true, requirements="\d+", default="-1", description="Identifier")
     * @Rest\QueryParam(name="active", requirements="\d?", default="1", description="Active items")
     * @Rest\QueryParam(name="from", requirements="\d{4}-\d{2}-\d{2}", default="0000-00-00", description="From date")
     * @Rest\QueryParam(name="to", requirements="\d{4}-\d{2}-\d{2}", default="0000-00-00", description="End date")
     * @Rest\QueryParam(name="labels", array=true, requirements="\d+", default="-1", description="Labels under which items have been classifed")
     *
     * @Rest\View()
     *
     * @param  ParamFetcher                                          $paramFetcher
     */
    public function getItemsAction(ParamFetcher $paramFetcher) {
        $parameters = $paramFetcher->all();

        // returns array which will be converted to json contents by FOSRestBundle
        return $this->getResource($parameters);
    }
}

P.S. : You will need to add a view to display the resource as an HTML page

Th. Ma.
  • 9,432
  • 5
  • 31
  • 46
  • 5
    The documentation and Liip bundle are both fairly limited in terms of actual content/examples. Post some examples of advanced usage of this bundle, I'll award you the bounty. For instance, custom route usage (Route, Get, Post, etc), the "magic" addition of the request format to routes, a solid example of how to use the view listener for json & html while returning an array/object from your action. – Jon L. Apr 09 '13 at 01:17
  • 1
    I think is great the solution, but I'm looking for others where params injection occurs, similar to .yml files (%the_date%) but in FOS Controller's action annotation instead, that param will be self initialized. Could be done? Please, check the full question: https://github.com/FriendsOfSymfony/FOSRestBundle/issues/774 – Felix Aballi May 20 '14 at 19:35
  • @Félix, you might want to overload the `QueryParam` class. – Th. Ma. May 20 '14 at 20:01
  • @ThierryMarianne, where can i find more facts? – Felix Aballi May 20 '14 at 20:08
  • @Félix, you might want to study the original `QueryParam` https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Controller/Annotations/Param.php – Th. Ma. May 20 '14 at 20:14
  • @ThierryMarianne, I read it. But it doesn't tell how to extend Param class. Any example available? – Felix Aballi May 20 '14 at 20:26
  • @Félix Tests of ParamFetcher and other classes can also be of great help to understand how the classes relate altogether and how they could be extended https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Tests/Request/ParamFetcherTest.php – Th. Ma. May 20 '14 at 20:30
  • All those links are completely outdated and are irrelevant – Pedro Luz Feb 02 '15 at 23:40
-5

you are missing the routing part of FOSRestbundle in the controller:

protected function postDatasetAction(Request $request){

  //Query here

} // "post_dataset"      [POST] /dataset
Kioko Kiaza
  • 1,378
  • 8
  • 28
  • 57