Lumen microservice generates swagger document

Time:2020-11-4

Lumen microservice generates swagger document

As a PHPer, when using lumen framework to develop microservices, it is necessary to write API documents. The more popular way is to use swagger to write API documents, but it supports annotation with Java language Different, PHP can only maintain a single swagger document, or add annotations to the comments to achieve similar functions. However, it is very painful to write swagger annotations in comments. There is no code prompt and no format.

This article will show you how to use the annotations plug-in in phpstorm to quickly create swagger documents when developing lumen microservice projects (larravel project is similar to other PHP projects).

This article will continue to revise and update, the latest content please refer to myGITHUBOn theProgram ape growth planProject, welcome star, more wonderful content pleasefollow me

Framework configuration

We use the latest lumen 5.7 to demonstrate. The demo code has been put into GitHub. If you are interested, you can refer to it

https://github.com/mylxsw/lumen-swagger-demo

Installation dependency

In the lumen project, you first need to install the swaggerlume project dependencies using composer

composer require darkaonline/swagger-lume

Lumen microservice generates swagger document

Project configuration

staybootstrap/app.phpIn the file, remove the comments for the configuration below (about 26 lines) and enable facade support.

$app->withFacades();

EnableSwaggerLumeThe configuration file of the project, in theRegister Container BindingsSection front, add

$app->configure('swagger-lume');

Then, in theRegister Service ProvidersSection, registrationSwaggerLumeServiceprovider for

$app->register(\SwaggerLume\ServiceProvider::class);

At the root of the project, execute the commandphp artisan swagger-lume:publishRelated configuration of Agger

Lumen microservice generates swagger document

After executing the order, the following changes are mainly reflected

Lumen microservice generates swagger document

  • stayconfig/Directory, the configuration file of the project is addedswagger-lume.php
  • stayresources/views/vendorDirectory, generatedswagger-lume/index.blade.phpView file, used to preview the generated API document

From the configuration file, we can get the following key information

  • api.titleThe generated API document displays the title
  • routes.apiThe routing address used to access the generated API document UI is by default/api/documentation
  • routes.docsIt is used to access the original API document generated in JSON format. The default routing address is/docs
  • paths.docsandpaths.docs_jsonComposition generation API- docs.json The address of the file. The default isstorage/api-docs/api-docs.json, executephp artisan swagger-lume:generateCommand, the file is generated

Syntax auto prompt

The pure handwritten swagger annotation is definitely undesirable. It is too easy to make mistakes, and we need to keep looking at the document reference syntax. Therefore, it is necessary to install a plug-in that can automatically prompt the annotation syntax in the annotation. Our common IDE isphpstormIn phpstorm, you need to installPHP annotationplug-in unit

Lumen microservice generates swagger document

After installing the plug-in, when we write the swagger document, we will have the code auto prompt function

Lumen microservice generates swagger document

Writing documents

Swagger documentation contains a lot of information that has nothing to do with the specific APIapp/Http/ControllersCreate aSwaggerControllerIn this controller, we do not implement business logic, but only use to place general document information

<?php
namespace App\Http\Controllers;

use OpenApi\Annotations\Contact;
use OpenApi\Annotations\Info;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Schema;
use OpenApi\Annotations\Server;

/**
 *
 * @Info(
 *     version="1.0.0",
 *    ,
 *Description = "this is a demo service, which provides the function of demonstrating the swagger API". ",
 *     @Contact(
 *         email="[email protected]",
 *         name="mylxsw"
 *     )
 * )
 *
 * @Server(
 *     url="http://localhost",
 *Description = "development environment",
 * )
 *
 * @Schema(
 *     schema="ApiResponse",
 *     type="object",
 *Description = "response entity, response results use this structure uniformly",
 *    ,
 *     @Property(
 *         property="code",
 *         type="string",
 *Description = "response code"
 *     ),
 *"Response (response)"
 * )
 *
 *
 * @package App\Http\Controllers
 */
class SwaggerController
{}

Next, in the business logic controller, we can write the API

<?php
namespace App\Http\Controllers;

use App\Http\Responses\DemoAdditionalProperty;
use App\Http\Responses\DemoResp;
use Illuminate\Http\Request;
use OpenApi\Annotations\Get;
use OpenApi\Annotations\MediaType;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\RequestBody;
use OpenApi\Annotations\Response;
use OpenApi\Annotations\Schema;

class ExampleController extends Controller
{

    /**
     * @Get(
     *     path="/demo",
     *Tags = {demo "},
     *Summary = demo API,
     *     @RequestBody(
     *         @MediaType(
     *             mediaType="application/json",
     *             @Schema(
     *                 required={"name", "age"},
     *@ property (property = name, type = string, description = "name"),
     *@ property (property = "age", type = "integer", description = "age"),
     *@ property (property = gender, type = string, description = gender)
     *             )
     *         )
     *     ),
     *     @Response(
     *         response="200",
     *Description = "normal operation response",
     *         @MediaType(
     *             mediaType="application/json",
     *             @Schema(
     *                 allOf={
     *                     @Schema(ref="#/components/schemas/ApiResponse"),
     *                     @Schema(
     *                         type="object",
     *                         @Property(property="data", ref="#/components/schemas/DemoResp")
     *                     )
     *                 }
     *             )
     *         )
     *     )
     * )
     *
     * @param Request $request
     *
     * @return DemoResp
     */
    public function example(Request $request)
    {
        //Todo business logic

        $resp         = new DemoResp();
        $resp->name   = $request->input('name');
        $resp->id     = 123;
        $resp->age    = $request->input('age');
        $resp->gender = $request->input('gender');

        $prop1        = new DemoAdditionalProperty();
        $prop1->key   = "foo";
        $prop1->value = "bar";

        $prop2        = new DemoAdditionalProperty();
        $prop2->key   = "foo2";
        $prop2->value = "bar2";

        $resp->properties = [$prop1, $prop2];

        return $resp;
    }
}

Here, in the response results, we refer to theApiResponse, also refers to an undefinedExampleRespObject, we canapp\Http\ResponsesThe exampleresp object is implemented in the directory (created by ourselves), and we put all the response objects in this directory

<?php

namespace App\Http\Responses;

use OpenApi\Annotations\Items;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Schema;

/**
 * @Schema(
 *    ,
 *Description = "demo response content description"
 * )
 *
 * @package App\Http\Responses
 */
class DemoResp extends JsonResponse
{

    /**
     * @Property(
     *     type="integer",
     *     description="ID"
     * )
     *
     * @var int
     */
    public $id = 0;

    /**
     * @Property(
     *     type="string",
     *Description = "user name"
     * )
     *
     * @var string
     */
    public $name;

    /**
     * @Property(
     *     type="integer",
     *Description = "age"
     * )
     *
     * @var integer
     */
    public $age;

    /**
     * @Property(
     *     type="string",
     *Description = "gender"
     * )
     *
     * @var string
     */
    public $gender;

    /**
     * @Property(
     *     type="array",
     *     @Items(ref="#/components/schemas/DemoAdditionalProperty")
     * )
     *
     * @var array
     */
    public $properties = [];
}

Return object references other objects

<?php
namespace App\Http\Responses;

use OpenApi\Annotations\Property;
use OpenApi\Annotations\Schema;

/**
 *
 * @Schema(
 *    ,
 *Description = "additional attribute description"
 * )
 *
 * @package App\Http\Responses
 */
class DemoAdditionalProperty
{
    /**
     * @Property(
     *     type="string",
     *     description="KEY"
     * )
     *
     * @var string
     */
    public $key;

    /**
     * @Property(
     *     type="string",
     *     description="VALUE"
     * )
     *
     * @var string
     */
    public $value;
}

Generating documents

Execute the following command to generate the document. The generated document is in thestorage/api-docs/api-docs.json

php artisan swagger-lume:generate

preview files

Open browser accessHttp: / / access address / docYou can see below

Lumen microservice generates swagger document

visitHttp: / / access address / API / documentationWe see

Lumen microservice generates swagger document

Interface details expansion

Lumen microservice generates swagger document

more

This paper describes how to use code annotation to generate swagger document automatically in lumen project, and cooperate with the code prompt function of phpstorm. However, it is not enough to learn these. You also need to understand the syntax structure of swagger documentswagger-phpProject’sExamplesThere are many examples in the directory. You can refer to them.

Swagger documents are used in team projects, but there must be a place to manage documents. Here is a recommendationWizardProject, the project is a document management tool for team collaboration, supporting markdown documents and swagger documents. If you are interested, try it.

Recommended Today

. net Maui preview 5 function Preview

Although Microsoft build has just passed, we will continue to share our continuous progress in. Net multi platform application UI (. Net Maui). In this release, we have enabled animation and view transformation, completed the migration of multiple UI components, and improved a single project template.We also released the first batch of preview documents covering […]