docs/en/swagger.md
The hyperf/swagger component is based on zircote/swagger-php for packaging
For a full list of supported annotations, see the OpenApi\Annotations namespace or Documentation site
composer require hyperf/swagger
php bin/hyperf.php vendor:publish hyperf/swagger
| parameter name | role |
|---|---|
| enable | Enables or disables the Swagger document generator |
| port | The port number of the Swagger document generator |
| json_dir | The directory where JSON files generated by the Swagger Document Generator are stored |
| html | Path to the HTML file generated by the Swagger document generator |
| url | The URL path to the Swagger document |
| auto_generate | Whether to automatically generate Swagger documents |
| scan.paths | The path to the API interface file to be scanned, an array |
If auto_generate is configured, the documentation will be generated automatically in the framework initialisation event, without the need to call
php bin/hyperf.php gen:swagger
The SA namespaces that appear below are
use Hyperf\Swagger\Annotation as SA
The framework can start multiple servers, and the routes of each server can be distinguished based on the SA\HyperfServer annotation, and generate different swagger files (using that configuration as the file name).
It can be configured on the controller class or method:
#[SA\HyperfServer('http')]
#[SA\Post(path: '/test', summary: 'POST form example', tags: ['Api/Test'])]
#[SA\RequestBody(
description: 'Request parameters'.
content: [
new SA\MediaType(
mediaType: 'application/x-www-form-urlencoded'.
schema: new SA\Schema(
required: ['username', 'age'].
properties: [
new SA\Property(property: 'username', description: 'User name field description', type: 'string').
new SA\Property(property: 'age', description: 'Age field description', type: 'string').
new SA\Property(property: 'city', description: 'City field description', type: 'string').
]
).
).
].
)]
#[SA\Response(response: 200, description: 'Description of the returned value')]
public function test()
{
}
#[SA\Get(path: '/test', summary: 'GET example', tags: ['Api/Test'])]
#[SA\Parameter(name: 'username', description: 'User name field description', in : 'query', required: true, schema: new SA\Schema(type: 'string'))]
#[SA\Parameter(name: 'age', description: 'Age field description', in : 'query', required: true, schema: new SA\Schema(type: 'string'))]
#[SA\Parameter(name: 'city', description: 'City field description', in : 'query', required: false, schema: new SA\Schema(type: 'string'))]
#[SA\Response(
response: 200.
description: 'Description of the returned value'.
content: new SA\JsonContent(
example: '{"code":200, "data":[]}'
).
)]
public function list(ConversationRequest $request): array
{
}
In the SA\Property and SA\QueryParameter annotation, we can add rules parameters,
and then cooperate with SwaggerRequest to verify the validity of the parameters in the middleware.
<?php
namespace App\Controller;
use App\Schema\SavedSchema;
use Hyperf\Swagger\Request\SwaggerRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Swagger\Annotation as SA;
#[SA\HyperfServer(name: 'http')]
class CardController extends Controller
{
#[SA\Post('/user/save', summary: 'Save user info', tags: ['user-management'])]
#[SA\QueryParameter(name: 'token', description: 'auth token', type: 'string', rules: 'required|string')]
#[SA\RequestBody(content: new SA\JsonContent(properties: [
new SA\Property(property: 'nickname', type: 'integer', rules: 'required|string'),
new SA\Property(property: 'gender', type: 'integer', rules: 'required|integer|in:0,1,2'),
]))]
#[SA\Response(response: '200', content: new SA\JsonContent(ref: '#/components/schemas/SavedSchema'))]
public function info(SwaggerRequest $request)
{
$result = $this->service->save($request->all());
return $this->response->success($result);
}
}
The following is the default Swagger front-end page. You can modify the 'swagger.html' configuration to change it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerUI"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.hyperf.wiki/[email protected]/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.hyperf.wiki/[email protected]/swagger-ui-bundle.js" crossorigin></script>
<script src="https://unpkg.hyperf.wiki/[email protected]/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: GetQueryString("search"),
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
});
};
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = decodeURIComponent(r[2]);
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "/http.json" : context;
}
</script>
</body>
</html>
For example. when the domain unpkg.hyperf.wiki cannot work, you can replace it into unpkg.com.
<?php
declare(strict_types=1);
return [
'enable' => true,
'port' => 9500,
'json_dir' => BASE_PATH . '/storage/swagger',
'html' => <<<'HTML'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerUI"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/[email protected]/swagger-ui-bundle.js" crossorigin></script>
<script src="https://unpkg.com/[email protected]/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: GetQueryString("search"),
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
});
};
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = decodeURIComponent(r[2]);
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "/http.json" : context;
}
</script>
</body>
</html>
HTML,
'url' => '/swagger',
'auto_generate' => true,
'scan' => [
'paths' => null,
],
];