srio/api-doc-bundle

从注释生成REST API文档

安装: 137

依赖者: 0

建议者: 0

安全: 0

星星: 0

关注者: 3

分支: 834

类型:symfony-bundle

2.4.2 2013-11-14 16:01 UTC

README

Build Status

NelmioApiDocBundle 插件允许您为API生成良好的文档。

重要: 此插件与 symfony 的存储库 同步开发。对于 Symfony 2.0.x,您需要使用插件的 1.* 版本。

安装

将此插件添加到您的 composer.json 文件中

{
    "require": {
        "nelmio/api-doc-bundle": "dev-master"
    }
}

app/AppKernel.php 中注册该插件

// app/AppKernel.php
public function registerBundles()
{
    return array(
        // ...
        new Nelmio\ApiDocBundle\NelmioApiDocBundle(),
    );
}

routing.yml 中导入路由定义

# app/config/routing.yml
NelmioApiDocBundle:
    resource: "@NelmioApiDocBundle/Resources/config/routing.yml"
    prefix:   /api/doc

app/config/config.yml 中启用插件的配置

# app/config/config.yml
nelmio_api_doc: ~

使用方法

文档的主要问题是保持其更新。这就是为什么 NelmioApiDocBundle 大量使用反射。多亏了注释,记录API方法变得非常简单。

ApiDoc() 注释

该插件为控制器提供了 ApiDoc() 注释。

<?php

namespace Your\Namespace;

use Nelmio\ApiDocBundle\Annotation\ApiDoc;

class YourController extends Controller
{
    /**
     * This the documentation description of your method, it will appear
     * on a specific pane. It will read all the text until the first
     * annotation.
     *
     * @ApiDoc(
     *  resource=true,
     *  description="This is a description of your API method",
     *  filters={
     *      {"name"="a-filter", "dataType"="integer"},
     *      {"name"="another-filter", "dataType"="string", "pattern"="(foo|bar) ASC|DESC"}
     *  }
     * )
     */
    public function getAction()
    {
    }

    /**
     * @ApiDoc(
     *  description="Create a new Object",
     *  input="Your\Namespace\Form\Type\YourType",
     *  output="Your\Namespace\Class"
     * )
     */
    public function postAction()
    {
    }

    /**
     * @ApiDoc(
     *  description="Returns a collection of Object",
     *  requirements={
     *      {
     *          "name"="limit",
     *          "dataType"="integer",
     *          "requirement"="\d+",
     *          "description"="how many objects to return"
     *      }
     *  },
     *  parameters={
     *      {"name"="categoryId", "dataType"="integer", "required"=true, "description"="category id"}
     *  }
     * )
     */
    public function cgetAction($id)
    {
    }
}

以下属性可用

  • section:允许分组资源

  • resource:方法是否描述了主要资源(默认:false);

  • description:API方法的描述;

  • deprecated:允许将方法设置为已弃用(默认:false);

  • filters:过滤器数组;

  • requirements:要求数组;

  • parameters:参数数组;

  • input:与方法相关联的输入类型(目前支持表单类型、具有JMS序列化元数据的类以及具有验证组件元数据的类),对于 POST|PUT 方法很有用,可以是FQCN或表单类型(如果它在容器中的表单工厂中注册)。

  • output:与响应相关联的输出类型。与 input 以相同的方式指定和解析。

  • statusCodes:HTTP状态码数组及其返回该状态的时间描述;示例

<?php

class YourController
{
    /**
     * @ApiDoc(
     *     statusCodes={
     *         200="Returned when successful",
     *         403="Returned when the user is not authorized to say hello",
     *         404={
     *           "Returned when the user is not found",
     *           "Returned when somehting else is not found"
     *         }
     *     }
     * )
     */
    public function myFunction()
    {
        // ...
    }
}

每个 过滤器 必须定义一个 name 参数,但其他参数是自由的。过滤器通常是可选参数,您可以按自己的方式记录它们,但请注意在整个文档中保持一致性。

如果您设置 input,则插件会自动根据给定的类型提取参数,并确定每个参数的数据类型以及是否必需。

对于使用JMS元数据解析的类,如果可用,将使用属性的文档注释。

对于表单类型,您可以在每个字段上添加一个名为 description 的额外选项

<?php

class YourType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('note', null, array(
            'description' => 'this is a note',
        ));

        // ...
    }
}

该插件还会从路由定义(requirementspattern 等)中获取信息,因此要充分利用它,您应该定义严格的方法要求等。

其他插件注释

该插件还会从其他注释中获取信息

  • @FOS\RestBundle\Controller\Annotations\RequestParam - 用作 parameters

  • @FOS\RestBundle\Controller\Annotations\QueryParam - 用作 requirements(当严格参数为真时),filters(当严格为假时)

  • @JMS\SecurityExtraBundle\Annotation\Secure - 将 authentification 设置为 true

  • @Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache - 设置 cache

PHPDoc

标记为 @deprecated 的路由函数将在文档中将方法设置为弃用。

JMS序列化器功能

该插件支持JMS序列化器的一些功能,并在生成的文档中使用这些额外信息。

分组排除策略

如果你的类使用了JMS Group Exclusion Strategy,你可以通过以下语法指定在生成文档时使用哪些组:

input={
    "class"="Acme\Bundle\Entity\User",
    "groups"={"update", "public"}
}

在这种情况下,使用了'update'和'public'组。

该功能也适用于output属性。

对象版本化

如果你的output类使用了JMS Serializer的版本化功能,在生成文档时会自动使用版本化信息。

表单类型功能

如果你使用FormFactoryInterface::createdNamed('', 'your_form_type'),则默认情况下,文档将使用表单类型名称作为前缀(your_form_type[param] ... 而不是仅仅是param)。

你可以通过name键指定要使用的哪个前缀

input = {
 "class" = "your_form_type",
 "name" = ""
}

即时文档

通过调用带有参数?_doc=1的URL,如果有的话,你可以获得相应的文档。

网络界面

您可以在以下位置浏览整个文档:http://example.org/api/doc

命令

提供了一个命令,可以将文档以jsonmarkdownhtml格式导出。

php app/console api:doc:dump [--format="..."]

--format选项允许选择格式(默认为:markdown)。

例如,要生成静态版本的文档,可以使用:

php app/console api:doc:dump --format=html > api.html

默认情况下,生成的HTML将添加sandbox功能,除非你在配置中禁用它。如果你想生成不带sandbox的静态版本文档,请使用--no-sandbox选项。

配置

你可以指定自己的API名称

# app/config/config.yml
nelmio_api_doc:
    name: My API

此包提供了一个沙盒模式以测试API方法。您可以使用以下参数配置此沙盒

# app/config/config.yml
nelmio_api_doc:
    sandbox:
        authentication: # default null, if set, the value of the api key is read from the query string and appended to every sandbox api call
            name: access_token
            delivery: query # query or http_basic are supported
            custom_endpoint: true # default false, if true, your user will be able to specify its own endpoint
        enabled:  true # default: true, you can set this parameter to `false` to disable the sandbox
        endpoint: http://sandbox.example.com/ # default: /app_dev.php, use this parameter to define which URL to call through the sandbox
        accept_type: application/json # default null, if set, the value is automatically populated as the Accept header
        body_format: form # default form, determines whether to send x-www-form-urlencoded data or json-encoded data in sandbox requests
        request_format:
            method: format_param # default format_param, alternately accept_header, decides how to request the response format
            default_format: json # default json, alternately xml, determines which content format to request back by default

该包提供了一种注册多个input解析器的方法。第一个可以处理指定输入的解析器将被使用,因此您可以通过容器标签配置它们的优先级。以下是一个解析器服务注册的示例

#app/config/config.yml
services:
    mybundle.api_doc.extractor.custom_parser:
        class: MyBundle\Parser\CustomDocParser
        tags:
            - { name: nelmio_api_doc.extractor.parser, priority: 2 }

您还可以定义自己的motd内容(在方法列表上方)。您只需将其添加到配置中即可

#app/config/config.yml
nelmio_api_doc:
    # ...
    motd:
        template: AcmeApiBundle::Components/motd.html.twig

使用您自己的注解

如果您开发了与项目相关的自定义注解,并且希望将它们解析到ApiDoc中,您可以为服务提供自定义处理程序。您只需实现Nelmio\ApiDocBundle\Extractor\HandlerInterface并标记为nelmio_api_doc.extractor.handler

# app/config/config.yml
services:
    mybundle.api_doc.extractor.my_annotation_handler:
        class: MyBundle\AnnotationHandler\MyAnnotationHandler
        tags:
            - { name: nelmio_api_doc.extractor.handler }

查看内置的处理程序

致谢

设计在很大程度上受到了swagger-ui项目的启发。一些图标来自Glyphicons库,用于渲染文档。