Back to Hyperf

Hyperf Swagger

docs/en/swagger.md

3.1.687.6 KB
Original Source

Hyperf Swagger

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

Installation

composer require hyperf/swagger

Configure

php bin/hyperf.php vendor:publish hyperf/swagger
parameter namerole
enableEnables or disables the Swagger document generator
portThe port number of the Swagger document generator
json_dirThe directory where JSON files generated by the Swagger Document Generator are stored
htmlPath to the HTML file generated by the Swagger document generator
urlThe URL path to the Swagger document
auto_generateWhether to automatically generate Swagger documents
scan.pathsThe path to the API interface file to be scanned, an array

Generate documentation

If auto_generate is configured, the documentation will be generated automatically in the framework initialisation event, without the need to call

shell
php bin/hyperf.php gen:swagger

Use

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:

php
#[SA\HyperfServer('http')]
php
#[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()
{
}
php
#[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
{
}

Combination validator

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
<?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);
    }
}

Replace Swagger Dashboard

The following is the default Swagger front-end page. You can modify the 'swagger.html' configuration to change it.

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.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
<?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,
    ],
];