Yii2 OpenApi Specification Reader 模å ¶
åçæ¯éç¨phpç注éæ¥åapiææ¡£ï¼æ³¨éçè¯æ³éç¨php annotationæ¹å¼è¿è¡è§£æã 解æå符åOpenAPI Specification è§èï¼å¯ä»¥éè¿ swagger UI æ Redoc è¿è¡æ¸²ææå¯è¯»æ§å¼ºå¸¦æ交äºçapiææ¡£ã
swagger UI
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
'modules' => [
...
'openapireader' => [
'class' => \bestyii\openapiReader\Module::class,
'defaultDoc'=>'api',
'path' => [
'api'=>'@app/modules/api',
'openwork'=>'@app/modules/openwork',
'group' => [
'@grazio/api',
'@grazio/leads'
]
],
// disable page with your logic
'isDisable' => function () {
return false;
},
// replace placeholders in swagger content
'afterRender' => function ($content) {
$content = str_replace(
[
'{{SERVER_DESCRIPTION}}',
'{{HOST}}',
'{{BASE_PATH}}'
],
[
'Localhost',
Yii::$app->request->hostInfo,
'/api'
], $content);
return $content;
}
]
...
],
ç°å¨å°±å¯ä»¥è®¿é®ä½ çAPIææ¡£äº
# swagger é£æ ¼
http://yoururl.com/openapireader
# redoc é£æ ¼
http://yoururl.com/openapireader/default/redoc
ç¤ºä¾ Module
`
php
/**
- @OA\OpenApi(
- @OA\Info(
- 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 or on irc.freenode.net, #swagger. For this sample, you can use the Bearer
access token
to test the authorization filters.", - ),
- @OA\Server(
- description="Test",
- url="http://api.bestyii.com/api/"
- ),
- @OA\Server(
- description="Prod",
- url="http://api.bestyii.com/v2/"
- ),
- @OA\ExternalDocumentation(
- description="æ´å¤å ³äºè¾¾å¡æçä¿¡æ¯",
- url="http://bestyii.com"
- )
- ) */
/**
- @OA\SecurityScheme(
- securityScheme="bearerAuth",
- type="http",
- scheme="bearer",
- in="header",
- bearerFormat="JWT"
- )
- https://swagger.io/docs/specification/authentication/basic-authentication/ */
示ä¾<?php
namespace app\modules\api\controllers;
use app\modules\api\models\UserIdentity;
use Yii;
use app\modules\api\models\User;
use yii\data\ActiveDataProvider;
use app\modules\api\components\ActiveController;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
/**
* @OA\Tag(
* name="Users",
* description="ç¨æ·è´¦å·",
* @OA\ExternalDocumentation(
* description="æ´å¤ç¸å
³",
* url="http://bestyii.com"
* )
* )
*/
class UserController extends ActiveController
{
public $modelClass = 'app\modules\api\models\UserIdentity';
/**
* @OA\Get(
* path="/users",
* summary="æ¥è¯¢ User",
* tags={"Users"},
* description="",
* operationId="findUser",
* @OA\Parameter(
* name="ids",
* in="query",
* description="éå·éå¼ç id",
* required=false,
* @OA\Schema(
* type="integer",
* @OA\Items(type="int20"),
* ),
* ),
* @OA\Response(
* response=200,
* description="æ¥è¯¢æå",
* @OA\Schema(
* type="array",
* @OA\Items(ref="#/components/schemas/User")
* ),
* ),
* @OA\Response(
* response="400",
* description="æ æçid",
* ),
* security={{
* "bearerAuth":{}
* }}
* )
*/
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => UserIdentity::find(),
]);
return $dataProvider;
}
/**
* @OA\Get(
* path="/users/{id}",
* summary="éè¿IDæ¾ç¤ºè¯¦æ
",
* description="",
* operationId="getUserById",
* tags={"Users"},
* @OA\Parameter(
* description="id",
* in="path",
* name="id",
* required=true,
* @OA\Schema(
* type="integer",
* format="int64"
* )
* ),
* @OA\Response(
* response=200,
* description="æä½æå",
* @OA\JsonContent(ref="#/components/schemas/User")
* ),
* @OA\Response(
* response="400",
* description="æ æçID"
* ),
* @OA\Response(
* response="404",
* description="没ææ¾å°ç¸åºèµæº"
* ),
* security={{
* "bearerAuth":{}
* }}
* )
*/
public function actionView($id)
{
return $this->findModel($id);
}
/**
* @OA\Post(
* path="/users",
* tags={"Users"},
* operationId="addUser",
* summary="æ·»å ",
* description="",
* @OA\RequestBody(
* required=true,
* description="å建 User 对象",
* @OA\JsonContent(ref="#/components/schemas/User"),
* @OA\MediaType(
* mediaType="application/x-www-form-urlencoded",
* @OA\Schema(
* type="object",
* ref="#/components/schemas/User"
* ),
* )
* ),
* @OA\Response(
* response=201,
* description="æä½æå",
* @OA\JsonContent(ref="#/components/schemas/User")
* ),
* @OA\Response(
* 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;
}
/**
* @OA\Put(
* path="/users/{id}",
* tags={"Users"},
* operationId="updateUserById",
* summary="æ´æ°æå®IDæ°æ®",
* description="",
* @OA\Parameter(
* description="id",
* in="path",
* name="id",
* required=true,
* @OA\Schema(
* type="integer",
* format="int64"
* )
* ),
* @OA\RequestBody(
* required=true,
* description="æ´æ° User 对象",
* @OA\JsonContent(ref="#/components/schemas/User"),
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(ref="#/components/schemas/User")
* )
* ),
* @OA\Response(
* response=200,
* description="æä½æå",
* @OA\JsonContent(ref="#/components/schemas/User")
* ),
* @OA\Response(
* response=400,
* description="æ æçID",
* ),
* @OA\Response(
* response=404,
* description="没ææ¾å°ç¸åºèµæº",
* ),
* @OA\Response(
* 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;
}
/**
* @OA\Delete(
* path="/users/{id}",
* summary="å é¤User",
* description="",
* operationId="deleteUser",
* tags={"Users"},
* @OA\Parameter(
* description="éè¦å é¤æ°æ®çID",
* in="path",
* name="id",
* required=true,
* @OA\Schema(
* type="integer",
* format="int64"
* )
* ),
* @OA\Response(
* response=204,
* description="没ææ¾å°ç¸åºèµæº"
* ),
* @OA\Response(
* response=400,
* description="æ æçID"
* ),
* @OA\Response(
* 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
`
php
/**
- @OA\Schema(
- schema="User",
- required={"username"},
- @OA\Property(
- property="id",
- description="User ID",
- type="integer",
- format="int64",
- ),
- @OA\Property(
- property="username",
- description="ç¨æ·å",
- type="string",
- maxLength=100,
- ),
- @OA\Property(
- property="email",
- description="é®ç®±",
- type="string",
- maxLength=100,
- ),
- @OA\Property(
- property="password",
- description="å¯ç ",
- type="string",
- maxLength=64,
- ),
- @OA\Property(
- property="created_at",
- description="å建æ¶é´",
- type="string",
- default="0",
- ),
- @OA\Property(
- property="updated_at",
- description="æ´æ°æ¶é´",
- type="string",
- default="0",
- ),
- @OA\Property(
- property="last_login_at",
- description="æåç»å½æ¶é´",
- type="string",
- default="0",
- ),
- @OA\Property(
- property="ip",
- description="ç»å½IP ip2long",
- type="integer",
- format="int64",
- default=0,
- ),
)
/
TODO ¶
- add cache
- add customization
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.