PHP code example of webman-tech / swagger
1. Go to this page and download the library: Download webman-tech/swagger library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
webman-tech / swagger example snippets
namespace app\swagger;
use OpenApi\Annotations as OA;
/**
* @link https://swagger.io/specification/#info-object
* @OA\OpenApi(
* @OA\Info(version="1.0.0", title="My App"),
* @OA\Server(url="/api", description="localhost"),
* )
*/
class OpenapiSpec
{
}
use OpenApi\Annotations as OA;
'openapi_doc' => [
'modify' => function(OA\OpenApi $openApi) {
$openApi->info->title = 'My App';
$openApi->info->version = '1.0.0';
$openApi->servers = [
new OA\Server(['url' => '/api', 'description' => 'localhost']),
];
}
]
use Webman\Route;
use WebmanTech\Swagger\Swagger;
Route::group('/api1', function () {
(new Swagger())->registerRoute([
'route_prefix' => '/openapi',
'openapi_doc' => [
'scan_path' => app_path() . '/controller/api1',
],
]);
Route::get('/test', [\app\controller\Test::class, 'index']);
});
Route::group('/api2', function () {
(new Swagger())->registerRoute([
'route_prefix' => '/my-doc',
'openapi_doc' => [
'scan_path' => app_path() . '/controller/api2',
],
]);
Route::get('/test', [\app\controller\Test::class, 'index']);
});
use OpenApi\Attributes as OA;
use WebmanTech\Swagger\SchemaAnnotation\BaseSchema;
#[OA\Schema( public string $name = '';
#[OA\Property(description: '年龄', example: 5)]
public int $age = 0;
#[OA\Property(description: '备注', example: 'xxx')]
public string $remark = '';
protected function validationExtraRules() : array{
// 此处可自定义 校验规则
return [
'age' => 'max:100',
];
}
}
use OpenApi\Attributes as OA;
use WebmanTech\Swagger\DTO\SchemaConstants;
class IndexController {
#[OA\Post(
path: '/xxx',
summary: '接口说明',
requestBody: new OA\RequestBody(
n: 'null')]
public function md(Request $request) {
$schema = TestSchema::create($request->post(), validator()); // 自动装载加自动校验
// do something
return response();
}
#[OA\Get(
path: '/xxx',
summary: '接口说明',
x: [
SchemaConstants::X_SCHEMA_TO_PARAMETERS => TestSchema::class, // 该定义会自动将 Schema 转为 QueryParameters
],
)]
#[OA\Response(response: 200, description: 'null')]
public function md(Request $request) {
$schema = TestSchema::create($request->get(), validator()); // 自动装载加自动校验
// do something
return response();
}
}