如何使用FOSRestBundle以JSON格式返回或显示数据

雷尼埃

我正在使用Symfony2和FOSRestBundle在Restful API中工作。我已经阅读了视图层文档,但不清楚如何处理API的输出。我要实现的目标很简单:将结果显示或返回或输出为有效JSON。这是我在控制器上的功能:

<?php

/**
 * RestAPI:       Company.
 */
namespace PDI\PDOneBundle\Controller\Rest;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Controller\Annotations\Get;

class CompanyRestController extends FOSRestController
{
    /**
     * Gets all companies.
     *
     * @return array
     *
     * @ApiDoc(
     *   resource = true,
     *       https = true,
     *   description = "Gets all companies",
     *   statusCodes = {
     *      200 = "Returned when successful",
     *      400 = "Returned when errors"
     *   }
     * )
     * @Get("/api/v1/companies")
     *
     */
    public function getCompaniesAction()
    {
        $response = array();
        $em = $this->getDoctrine()->getManager();
        $entities = $em->getRepository('PDOneBundle:Company')->findAll();

        if ($entities) {
            foreach ($entities as $entity) {
                $response['companies'][] = [
                    'id' => $entity->getId(),
                    'createdAt' => $entity->getCreatedAt(),
                    'updatedAt' => $entity->getUpdatedAt(),
                    'name' => $entity->getName(),
                    'logo_url' => $entity->getLogoUrl(),
                    'division' => $entity->getDivision(),
                    'inactive' => $entity->getInactive(),
                ];
            }

            $response['status'] = 'ok';
        } else {
            $response['status'] = 'error';
        }

        return $response;
    }
}

如果我尝试此URL:/app_dev.php/api/v1/companies.json我收到404错误:

{"code":404,"message":"No route found for \"GET\/api\/v1\/companies.json\""}

如果我尝试以下URL:https://reptool.dev/app_dev.php/api/v1/companies错误打开:

找不到模板“”。500内部服务器错误-InvalidArgumentException 3个链接的异常:Twig_Error_Loader»InvalidArgumentException»InvalidArgumentException»

我也检查了FOSRestBundleByExample,但没有太多帮助。

我在这里想念的是什么?我如何实现我所需要的?有什么建议吗?

FOSRest配置

我忘记在以下位置添加FOSRestBundle config.yml

#FOSRestBundle
fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener:
        rules:
            - { path: ^/, priorities: [ json, html ], fallback_format: ~, prefer_extension: true }
        media_type:
            version_regex: '/(v|version)=(?P<version>[0-9\.]+)/'

    body_converter:
        enabled: true
        validate: 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

    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
胆小

我感到你很痛苦。我也很难入门。一个重要的起点是配置。这是我在实现中使用的。

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

format_listener如果你想JSON是默认响应,确保它的一套第一优先事项。否则,您的标题将需要Accept: application/json每次都包含这可能就是为什么在尝试使用细枝渲染HTML输出时出现细枝错误的原因。

另外,请确保已安装并包含在AppKernal中的序列化程序,例如http://jmsyst.com/bundles/JMSSerializerBundle

在您的控制器中,我发现像您所做的那样扩展FOSRestController最容易,但是它还返回一个视图对象而不是自己创建数组。串行器将为您处理所有这些。

/**
 * RestAPI:       Company.
 */
namespace PDI\PDOneBundle\Controller\Rest;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Controller\Annotations\Get;

class CompanyRestController extends FOSRestController
{
    /**
     * Gets all companies.
     *
     * @return array
     *
     * @ApiDoc(
     *   resource = true,
     *       https = true,
     *   description = "Gets all companies",
     *   statusCodes = {
     *      200 = "Returned when successful",
     *      400 = "Returned when errors"
     *   }
     * )
     * @Get("/api/v1/companies")
     *
     */
    public function getCompaniesAction()
    {
        $response = array();
        $em = $this->getDoctrine()->getManager();
        $entities = $em->getRepository('PDOneBundle:Company')->findAll();
        if(!$entities)
        {
             return $this->view(null, 400);
        }

        return $this->view($entities, 200);
    }
}

希望这会有帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用angularjs显示从控制器返回的json数据

来自分类Dev

如何返回数据框的json格式?

来自分类Dev

如何以json格式返回数据?

来自分类Dev

使用php的json数据显示格式

来自分类Dev

显示JSON格式数据

来自分类Dev

FOSRestBundle如何返回JsonResponse

来自分类Dev

FOSRestBundle如何返回JsonResponse

来自分类Dev

如何格式化和显示从AngularFire返回的Firestore数据?

来自分类Dev

如何使用AngularJS显示此JSON格式

来自分类Dev

如何在Android中使用RecyclerView从Web服务器显示JSON格式数据

来自分类Dev

如何直接从mysql数据库中获取图像并使用php以json格式显示它们?

来自分类Dev

如何使用Angular Js以从node.js服务器检索的表格式显示json数据

来自分类Dev

FOSRestBundle:如何配置后备格式

来自分类Dev

如何使用jQuery从JSON格式读取数据

来自分类Dev

如何使用 Python 提取 JSON 格式的数据

来自分类Dev

使用$ .getJSON以正确的格式从php为emberjs返回json数据

来自分类Dev

使用JavaScript以JSON格式从数据库返回DateTime

来自分类Dev

使用C#(HTTPWEBREQUEST)返回的JSON格式缺少数据

来自分类Dev

如何以数据表格式显示JSON?

来自分类Dev

如何从多个表中选择数据并以json格式显示?

来自分类Dev

如何使用python更改从csv调用的返回数据格式

来自分类Dev

如何使用angularjs以表格格式显示单列数据?

来自分类Dev

Excel:如何使用条件格式突出显示丢失的数据?

来自分类Dev

如何使用HTML敏捷性以正确的格式显示数据

来自分类Dev

如何使用if语句显示从csv导入的格式表Powershell数据?

来自分类Dev

如何使用FOSRestBundle和symfony表单处理嵌套的json

来自分类Dev

Select2-如何显示返回的JSON数据

来自分类Dev

如何使用javascript显示JSON数组数据?

来自分类Dev

如何使用javascript显示json数据

Related 相关文章

  1. 1

    如何使用angularjs显示从控制器返回的json数据

  2. 2

    如何返回数据框的json格式?

  3. 3

    如何以json格式返回数据?

  4. 4

    使用php的json数据显示格式

  5. 5

    显示JSON格式数据

  6. 6

    FOSRestBundle如何返回JsonResponse

  7. 7

    FOSRestBundle如何返回JsonResponse

  8. 8

    如何格式化和显示从AngularFire返回的Firestore数据?

  9. 9

    如何使用AngularJS显示此JSON格式

  10. 10

    如何在Android中使用RecyclerView从Web服务器显示JSON格式数据

  11. 11

    如何直接从mysql数据库中获取图像并使用php以json格式显示它们?

  12. 12

    如何使用Angular Js以从node.js服务器检索的表格式显示json数据

  13. 13

    FOSRestBundle:如何配置后备格式

  14. 14

    如何使用jQuery从JSON格式读取数据

  15. 15

    如何使用 Python 提取 JSON 格式的数据

  16. 16

    使用$ .getJSON以正确的格式从php为emberjs返回json数据

  17. 17

    使用JavaScript以JSON格式从数据库返回DateTime

  18. 18

    使用C#(HTTPWEBREQUEST)返回的JSON格式缺少数据

  19. 19

    如何以数据表格式显示JSON?

  20. 20

    如何从多个表中选择数据并以json格式显示?

  21. 21

    如何使用python更改从csv调用的返回数据格式

  22. 22

    如何使用angularjs以表格格式显示单列数据?

  23. 23

    Excel:如何使用条件格式突出显示丢失的数据?

  24. 24

    如何使用HTML敏捷性以正确的格式显示数据

  25. 25

    如何使用if语句显示从csv导入的格式表Powershell数据?

  26. 26

    如何使用FOSRestBundle和symfony表单处理嵌套的json

  27. 27

    Select2-如何显示返回的JSON数据

  28. 28

    如何使用javascript显示JSON数组数据?

  29. 29

    如何使用javascript显示json数据

热门标签

归档