How to return or display data in JSON format using FOSRestBundle

Asked
Active3 hr before
Viewed126 times

6 Answers

displayreturnusing
90%

I am working in a Restful API using Symfony2 and FOSRestBundle. I have read view layer docs but is not clear to me how to handle output for API. What I want to achieve is simple: display or return or output the result as valid JSON. This is what I have at controller:, Meta Stack Overflow , Stack Overflow Public questions & answers , Stack Overflow help chat

I feel your pain. I had troubles getting started as well. One important place to start is the config. Here's what I use in my implementation.

fos_rest:
    param_fetcher_listener: true
    view:
        mime_types:
            json: ['application/json', 'application/json;version=1.0', 'application/json;version=1.1']
        view_response_listener: 'force'
        formats:
            xml:  false
            json: true
        templating_formats:
            html: true
    format_listener:
        rules:
            - { path: ^/, priorities: [ json, html ], fallback_format: ~, prefer_extension: true }
        media_type:
            version_regex: '/(v|version)=(?P<version>[0-9\.]+)/'
    exception:
        codes:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
            'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
        messages:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
    allowed_methods_listener: true
    access_denied_listener:
        json: true
    body_listener: true
load more v
88%

The Album entity is almost identical to that from our basic Symfony 4 JSON API implementation. We won't need to implement \JsonSerializable.,I'm going to shamelessly copy / paste the AlbumType form from the Symfony 4 JSON API implementation:,This is not 100% identical to the previous Album entity implementation, as this time we need not implements \JsonSerializable.,This concludes all the prerequisite tasks needed to allow us to start the Symfony 4 with FOSRESTBundle implementation

By using the Maker Bundle we can make the entity class stub, and get the associated repository class generated for us for free:

bin / console make: entity Album

created: src / Entity / Album.php
created: src / Repository / AlbumRepository.php

Success!

   Next: Add more fields to your entity and start using it.
Find the documentation at https: //symfony.com/doc/current/doctrine.html#creating-an-entity-class
load more v
72%

OK thanks to you I got it working ! I still have to handle the error retrieving part by myself, but at least I can offer clients a useful error message. Thanks a lot for taking time to help me through that 👍,I use the body listener, that convert the request param from json (or whatever config you have) into a array, so it's transparent, you never deal with json in a controller this is a fosrestbundle responsability: http://symfony.com/doc/master/bundles/FOSRestBundle/body_listener.html,By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.,Using submit instead handlrRequest you can use an array and a clear missing second parameter to specify if the parameters not sent has to be nullify of not

    /**
     * @Route("/customers")
     * @ApiDoc(
     *      resource=false,
     *      input="NetDev\CoreBundle\Form\CustomerType",
     *      description="Create a new customer",
     *      section="Customers",
     *      statusCode={
     *          201="Action successful",
     *          403="Authorization required but incorrect / missing information or insufficient rights",
     *          500="Returned if action failed for unknown reasons"
     *      }
     *  )
     *
     * --View(template="NetDevRestBundle:Customers:add.json.twig", templateVar="form", statusCode=400)
     * @View(templateVar="form", statusCode=400)
     * @param Request $request
     * @return \FOS\RestBundle\View\View
     */
    public
    function postCustomerAction(Request $request) {
       $data = json_decode($request - > getContent(), true);
       $manager = $this - > getManager();
       $customer = new Customer();
       $form = $this - > getForm($customer);
       $form - > handleRequest($data);
       //$form->submit($data);
       if ($form - > isValid()) {
          $manager - > create($customer);
          return; /* will be redirected */
       }
       /* return $this->view((string)$form->getErrors())
               ->setTemplate('NetDevRestBundle:Common:form_error.json.twig'); */ // -> empty string
       return $form;
    }
load more v
65%

Besides the friendsofsymfony/rest-bundle, we also installed the sensio/framework-extra-bundle. It will help us to make code easier to read by using annotations for defining our routes. ,Now let’s install some necessary bundles with composer   ,In this Symfony 4 tutorial, we will create a basic server back-end structure for your application using the REST API architecture style. We will use a 'FOSRestBundle' bundle as a basis, implement 'get' and 'post' methods to create and show the list of resources respectively. Besides that, we will add the OAuth2 authentication with FOSOAuthServerBundle.,Create a user class for FOSUserBundle

composer create - project symfony / skeleton rest_api_project
load more v
75%

I want all API exceptions to be returned in a specific JSON format like this:,I'm using FOSRestBundle with Symfony 2 to implement a REST API in JSON format.,The exception_wrapper_handler config option was removed. Use normalizers instead.,You can write custom exception wrapper handler like in docs. In your case:

I want all API exceptions to be returned in a specific JSON format like this:

{
   "success": false,
   "exception": {
      "exceptionClass": "SomeNastyException",
      "message": "A nasty exception occurred"
   }
}
load more v
40%

Feel free to also add this exception to your DELETE and PUT methods. When we request a collection of articles. There is no need to throw an exception if nothing is found. We can just return empty array in that case.,We can also do a GET collection call. The only difference here is that we don’t provide an ID in our request.,Mastering best practices, patterns and architectures on the web,We want to separate the Rest controllers from our Web controllers

Lets start by installing the FOSRESTBundle. But before we can do that we need the Serializer Component to serialize or deserialize the resources of our application.

composer require symfony / serializer
load more v

Other "display-return" queries related to "How to return or display data in JSON format using FOSRestBundle"