2

I hope I post this question in good way. I was trying to find an answer in google and symfony docs, but nothing is helpful for me - maybe due to my symfony skills (I don't know this framework - I'm trying to study :) ).

My goal is to get article from database (I know how to do it so I skipped this action in code, prepare a view and return as json - I it's possible using FOSRestBundle

My symfony version is 3.3.9, FOSRestBundle: 2.2.0 My problem is that I have a rest api project with this configuration:

fos_rest:
    view:
        default_engine: twig
        view_response_listener: force
        force_redirects:
            html: true
#          xml: true
        formats:
            jsonp: true
            json: true
            xml: true
            rss: false
        templating_formats:
            html: true
            json: true
        mime_types:
            json: ['application/json', 'application/x-json', 'application/vnd.example-com.foo+json']
            rss: 'application/rss+xml'
            jpg: 'image/jpeg'
            png: 'image/png'
        jsonp_handler: ~
    body_listener: true
    param_fetcher_listener: force
    allowed_methods_listener: true
    access_denied_listener:
        json: true
    format_listener:
        rules:
            - { path: ^/api/v1, priorities: [html, json, xml], fallback_format: json, prefer_extension: false }
    routing_loader:
        default_format: ~
    exception:
        codes:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
            'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
        messages:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
    service:
        view_handler:         fos_rest.view_handler.default

My controller action looks:

/**
 * @ViewAnnotation()
 */
public function getArticleAction()
{
    $data = [
        'any' => 'any'
    ]; // get data, in this case list of users.

    $view = $this->view($data, 200)->setTemplate('MyBundle:Article:getArticles.html.twig');
    return $this->handleView($view);
}

The problem is that this code returns html instead of json. Moreover, for other controllers, which I don't want to render view for, I have this message:

Unable to find template "" (looked into: /var/www/html/app/Resources/views, /var/www/html/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form).

If I try to change config.yml (fos_rest section) my api returns: {"any":"any"}

I can use JsonResponse and do what I want by skipping FOSRestBundle, but I would like to understand and be able to use FOSRestBundle. Could anybody help me and write step by step how I can reach what I want or send me any suggestion what is wrong?

0 Answers0