timeinc / swagger-bundle
Swagger.php在Symfony中的实现
Requires
- symfony/symfony: ^2.7|^3.0
- zircote/swagger-php: ~2.0
Requires (Dev)
- phpunit/phpunit: ^4.8|^5.7
This package is not auto-updated.
Last update: 2024-09-24 21:31:08 UTC
README
此扩展包提供Swagger.php在Symfony中的集成。它应该在开发环境中运行,因为在运行时搜索注解并不高效。该扩展包具有生成swagger.json
文件的能力,该文件可以静态提供服务。
安装
通过Composer安装
composer require timeinc/swagger-bundle --dev
启用扩展包
在你的app/AppKernel.php
文件中,将以下内容添加到你的dev扩展包列表中
<?php class AppKernel extends Kernel { public function registerBundles() { // ... if (in_array($this->getEnvironment(), ['dev', 'test'], true)) { // ... $bundles[] = new TimeInc\SwaggerBundle\SwaggerBundle(); } // ... } }
配置扩展包
应用程序配置
打开./app/config/config_dev.yml
,并添加以下配置。
swagger: version: '2.0' info: title: 'My API' version: '1.0.0' description: 'My API Description' host: 'my-api-host:8080' base_path: '/v2' schemes: - https alternative_hosts: - { name: 'production', host: 'productionhost', schemes: [https], base_path: '/api' } produces: - application/json consumes: - application/json annotations: bundles: - AcmeDemoBundle pretty_json: true
完整的配置参考提供了所有值和默认值的完整列表。
路由
该扩展包包含查看默认swagger.json
模式或由预设定义的具有覆盖主机、方案和base_path的模式的路由。要启用路由,请在./app/config/routing_dev.yml
中添加以下内容
_swagger: resource: "@SwaggerBundle/Resources/config/routing.xml" prefix: /
您可以通过/_swagger/swagger.json
访问默认模式,或通过/_swagger/swagger-{alternative-host-name}.json
访问替代模式。如前所述,不应将此添加到生产路由中。
用法
一旦您在config_dev.yml
中将扩展包注册到swagger > bundles
下,swagger-bundle将自动在以下位置搜索任何swagger-php注解
- [bundle_dir]/Controller
- [bundle_dir]/Document
- [bundle_dir]/Entity
- [bundle_dir]/Form
- [bundle_dir]/Model
- [bundle_dir]/Swagger
请参阅swagger-php的注解参考以获取swagger-php语法的详细信息。
Symfony路由
此扩展包还包含一个额外的\TimeInc\SwaggerBundle\Swagger\Annotation\Route
注解,允许您将symfony路由定义为swagger端点。使用该注解将为每个方法设置swagger路径,并添加路径变量的参数以及任何默认值作为查询字符串。
注解可以定义在具有以下属性的类型或方法上
注意:如果省略了实体,则扩展包将在同一扩展包中搜索与控制器同名的实体名称。例如,以下示例控制器是
Acme\PetBundle\Controller\PetController
,因此扩展包将在Acme\PetBundle\Entity\Pet
中搜索实体。
<?php namespace Acme\PetBundle\Controller; use TimeInc\SwaggerBundle\Swagger\Annotation\Route; /** * @Route( * method="cgetAction", * route="api_get_pets", * returns="collection" * ) */ class PetController { /** * This annotation defines no entity. The bundle will check an entity exists in: * Acme\PetBundle\Entity\Pet * * @Route( * route="api_get_pet" * ) */ public function getAction() {} /** * @Route( * route="api_get_pet_owner", * entity="Acme\PetBundle\Entity\Owner", * headers={"X-TEST": "string"}, * queryParams={"query": "string", "page": "integer"} * ) */ public function getOwnerAction() {} }
命令行
您可以使用swagger:dump
命令将json模式输出到控制台
./bin/console -e=dev swagger:dump --pretty
提示:您可以使用选项
--alternative-host=product
来覆盖主机、方案和base_path,使用您的生产预设
API网关
该扩展包还可以使用HTTP代理生成AWS API Gateway的swagger模式。
然后可以将模式导入AWS控制台,以生成通过HTTP代理对API的1-1路由映射。所有参数和头部都会导入AWS并通过。
API网关
请参阅文档了解如何将API与API网关集成。