Yii2 OpenApi Specification Reader 模块
原理是采用php的注释来写api文档,注释的语法采用php annotation方式进行解析。 解析后符合OpenAPI Specification 规范,可以通过 swagger UI 或 Redoc 进行渲染成可读性强带有交互的api文档。
swagger UI
Redoc:
这个模块集成了:
swagger-php swagger-ui v3 Redocly/redoc安装 Installation
通过 composer安装.
项目中直接运行
php composer.phar require bestyii/yii2-openapi-reader:dev-master
或者添加下面代码到 composer.json
文件
"bestyii/yii2-openapi-reader": "dev-master"
使用 Usage
Once the extension is installed, simply use it in your code by :
You set url, where locate json file OR set path for scan
if (YII_ENV_DEV) { $config['modules']['openapireader'] = [ 'class' => bestyiiopenapiReaderModule::class, 'defaultDoc' => 'api', 'path' => [ 'api' => '@grazio/api', 'extensions' => '@app/extensions', ], // disable page with your logic 'isDisable' => function () { return false; }, // replace placeholders in swagger content 'afterRender' => function ($content) { $content = str_replace('{{HOST}}', yiihelpersUrl::base(true), $content); $content = str_replace('{{BASE_PATH}}', '/api', $content); $content = str_replace('{{SERVER_DESCRIPTION}}', 'description', $content); return $content; } ]; }
现在就可以访问你的API文档了
# swagger 风格
http://yoururl.com/openapireader
# redoc 风格
http://yoururl.com/openapireader/default/redoc
示例 Module
/** * @OAOpenApi( * @OAInfo( * version="0.0.1", * title="OpenApi", * description="This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the Bearer `access token` to test the authorization filters.", * ), * @OAServer( * description="Test", * url="http://api.bestyii.com/api/" * ), * @OAServer( * description="Prod", * url="http://api.bestyii.com/v2/" * ), * @OAExternalDocumentation( * description="更多关于达卡拉的信息", * url="http://bestyii.com" * ) * ) */ /** * @OASecurityScheme( * securityScheme="bearerAuth", * type="http", * scheme="bearer", * in="header", * bearerFormat="JWT" * ) * https://swagger.io/docs/specification/authentication/basic-authentication/ */
示例 controller
<?php namespace appmodulesapicontrollers; use appmodulesapimodelsUserIdentity; use Yii; use appmodulesapimodelsUser; use yiidataActiveDataProvider; use appmodulesapicomponentsActiveController; use yiiwebNotFoundHttpException; use yiiwebServerErrorHttpException; /** * @OATag( * name="Users", * description="用户账号", * @OAExternalDocumentation( * description="更多相关", * url="http://bestyii.com" * ) * ) */ class UserController extends ActiveController { public $modelClass = 'appmodulesapimodelsUserIdentity'; /** * @OAGet( * path="/users", * summary="查询 User", * tags={"Users"}, * description="", * operationId="findUser", * @OAParameter( * name="ids", * in="query", * description="逗号隔开的 id", * required=false, * @OASchema( * type="integer", * @OAItems(type="int20"), * ), * ), * @OAResponse( * response=200, * description="查询成功", * @OASchema( * type="array", * @OAItems(ref="#/components/schemas/User") * ), * ), * @OAResponse( * response="400", * description="无效的id", * ), * security={{ * "bearerAuth":{} * }} * ) */ public function actionIndex() { $dataProvider = new ActiveDataProvider([ 'query' => UserIdentity::find(), ]); return $dataProvider; } /** * @OAGet( * path="/users/{id}", * summary="通过ID显示详情", * description="", * operationId="getUserById", * tags={"Users"}, * @OAParameter( * description="id", * in="path", * name="id", * required=true, * @OASchema( * type="integer", * format="int64" * ) * ), * @OAResponse( * response=200, * description="操作成功", * @OAJsonContent(ref="#/components/schemas/User") * ), * @OAResponse( * response="400", * description="无效的ID" * ), * @OAResponse( * response="404", * description="没有找到相应资源" * ), * security={{ * "bearerAuth":{} * }} * ) */ public function actionView($id) { return $this->findModel($id); } /** * @OAPost( * path="/users", * tags={"Users"}, * operationId="addUser", * summary="添加", * description="", * @OARequestBody( * required=true, * description="创建 User 对象", * @OAJsonContent(ref="#/components/schemas/User"), * @OAMediaType( * mediaType="application/x-www-form-urlencoded", * @OASchema( * type="object", * ref="#/components/schemas/User" * ), * ) * ), * @OAResponse( * response=201, * description="操作成功", * @OAJsonContent(ref="#/components/schemas/User") * ), * @OAResponse( * response=405, * description="无效的输入", * ), * security={{ * "bearerAuth":{} * }} * ) */ public function actionCreate() { $model = new UserIdentity(); if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->save()) { $response = Yii::$app->getResponse(); $response->setStatusCode(201); } elseif (!$model->hasErrors()) { throw new ServerErrorHttpException('Failed to create the object for unknown reason.'); } return $model; } /** * @OAPut( * path="/users/{id}", * tags={"Users"}, * operationId="updateUserById", * summary="更新指定ID数据", * description="", * @OAParameter( * description="id", * in="path", * name="id", * required=true, * @OASchema( * type="integer", * format="int64" * ) * ), * @OARequestBody( * required=true, * description="更新 User 对象", * @OAJsonContent(ref="#/components/schemas/User"), * @OAMediaType( * mediaType="multipart/form-data", * @OASchema(ref="#/components/schemas/User") * ) * ), * @OAResponse( * response=200, * description="操作成功", * @OAJsonContent(ref="#/components/schemas/User") * ), * @OAResponse( * response=400, * description="无效的ID", * ), * @OAResponse( * response=404, * description="没有找到相应资源", * ), * @OAResponse( * response=405, * description="数据验证异常", * ), * security={{ * "bearerAuth":{} * }} * ) */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->getBodyParams(), '') && $model->save()) { Yii::$app->response->setStatusCode(200); } elseif (!$model->hasErrors()) { throw new ServerErrorHttpException('Failed to update the object for unknown reason.'); } return $model; } /** * @OADelete( * path="/users/{id}", * summary="删除User", * description="", * operationId="deleteUser", * tags={"Users"}, * @OAParameter( * description="需要删除数据的ID", * in="path", * name="id", * required=true, * @OASchema( * type="integer", * format="int64" * ) * ), * @OAResponse( * response=204, * description="没有找到相应资源" * ), * @OAResponse( * response=400, * description="无效的ID" * ), * @OAResponse( * response=404, * description="没有找到相应资源" * ), * security={{ * "bearerAuth":{} * }} * ) */ public function actionDelete($id) { $model = $this->findModel($id); if ($model->softDelete() === false) { throw new ServerErrorHttpException('Failed to delete the object for unknown reason.'); } Yii::$app->getResponse()->setStatusCode(204); } /** * Finds the User model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return User the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = UserIdentity::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException('The requested User does not exist.'); } }
示例 model
/** * @OASchema( * schema="User", * required={"username"}, * @OAProperty( * property="id", * description="User ID", * type="integer", * format="int64", * ), * @OAProperty( * property="username", * description="用户名", * type="string", * maxLength=100, * ), * @OAProperty( * property="email", * description="邮箱", * type="string", * maxLength=100, * ), * @OAProperty( * property="password", * description="密码", * type="string", * maxLength=64, * ), * @OAProperty( * property="created_at", * description="创建时间", * type="string", * default="0", * ), * @OAProperty( * property="updated_at", * description="更新时间", * type="string", * default="0", * ), * @OAProperty( * property="last_login_at", * description="最后登录时间", * type="string", * default="0", * ), * @OAProperty( * property="ip", * description="登录IP ip2long", * type="integer", * format="int64", * default=0, * ), *) */
TODO
add cache add customization
版权声明:
1、该文章(资料)来源于互联网公开信息,我方只是对该内容做点评,所分享的下载地址为原作者公开地址。2、网站不提供资料下载,如需下载请到原作者页面进行下载。
3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考学习用!
4、如文档内容存在违规,或者侵犯商业秘密、侵犯著作权等,请点击“违规举报”。