Home > PHP Framework > Laravel > Learn more about the use of Laravel Swagger

Learn more about the use of Laravel Swagger

WBOY
Release: 2022-04-11 20:54:10
forward
4291 people have browsed it

This article brings you relevant knowledge about laravel, which mainly introduces issues related to the use of Swagger. Let’s take a look at generating swagger based on Laravel as an example. I hope it will be helpful to everyone. help.

Learn more about the use of Laravel Swagger

[Related recommendations: laravel video tutorial]

swagger is too spicy?

This tutorial is based on Laravel generating swagger as an example. In fact, this thing is basically the same as a language or a framework, because they all use public json, and scan the "language" predetermined by swagger through the program. ”, the generated structure is stored in json and displayed through swagger ui (or developed by yourself).

For PHP developers, most students dislike swagger. Because this seems to be very troublesome to write. When I think about the code that can be written in PHP in minutes, it takes 10 minutes to write swagger, and I resist this thing in my heart.

Students who are involved in Java development know that most of them use swagger, because Java needs to maintain the data structure, and swagger is more flexible to integrate in Java.

At this time, if you see php in java saying that swagger is anti-human, it will be too troublesome. It is a product of ancient times. The Java friends around me will be secretly happy that they don’t use such useful things, and they also say that PHP is the best language in the world.

Why do I use swagger

I have been writing automatic code generation recently. In fact, Laravel now automatically generates CURD. For example, like laravel-admin, a command generates CURD, but after generation, the data looks very cold. For example, some fields do not need to be displayed, some need to be selected for associated enumerations, some are hasMany, and the overtrue (super) api scaffolding is also very good

Therefore, swaager can also write automated generation according to business needs

L5-Swagger

https://github.com/DarkaOnLine/L5-Swagger

Installation:

composer require "darkaonline/l5-swagger"
Copy after login

Use:

php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
php artisan l5-swagger:generate
Copy after login

Fill in the following example to generate and then access

/api/documentation
Copy after login

@OA\Info is required

Example

/**
 * @OA\Info(
 *      version="1.0.0",
 *      title="L5 OpenApi",
 *      description="L5 Swagger OpenApi description",
 *      @OA\Contact(
 *          email="darius@matulionis.lt"
 *      ),
 *     @OA\License(
 *         name="Apache 2.0",
 *         url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *     )
 * )
 */
Copy after login

get request

If you want to match the value in path, then in path query in query

/**
 * @OA\Get(
 *      path="/projects/{id}",
 *      operationId="getProjectById",
 *      tags={"Projects"},
 *      summary="Get project information",
 *      description="Returns project data",
 *      @OA\Parameter(
 *          name="id",
 *          description="Project id",
 *          required=true,
 *          in="path",
 *          @OA\Schema(
 *              type="integer"
 *          )
 *      ),
 *      @OA\Response(
 *          response=200,
 *          description="successful operation"
 *       ),
 *      @OA\Response(response=400, description="Bad request"),
 *      @OA\Response(response=404, description="Resource Not Found"),
 *      security={
 *         {
 *             "oauth2_security_example": {"write:projects", "read:projects"}
 *         }
 *     },
 * )
 */
Copy after login

POST request

              
    /**
     * @OA\Post(
     *      path="/api/test/store",
     *      operationId="api/test/store",
     *      tags={"Test"},
     *      summary="Test创建",
     *      description="Test提交创建",
     *      @OA\Parameter(
     *          name="id",
     *          description="",
     *          required=false,
     *          in="query",
     *      ),
     *     @OA\Response(
     *         response=200,
     *         description="successful operation",
     *         @OA\JsonContent(
     *         ref="#/components/schemas/Test"
     *         )
     *     ),
     *      @OA\Response(response=400, description="Bad request"),
     *      @OA\Response(response=404, description="Resource Not Found"),
     *      security={
     *         {
     *             "api_key":{}
     *         }
     *     },
     * )
     */
Copy after login

File upload parameters

     *     @OA\RequestBody(
     *       @OA\MediaType(
     *           mediaType="multipart/form-data",
     *           @OA\Schema(
     *               type="object",
     *               @OA\Property(
     *                  property="file",
     *                  type="file",
     *               ),
     *           ),
     *       )
     *     ),
Copy after login

Passed in as enumeration

     *     @OA\Parameter(
     *         name="status",
     *         in="query",
     *         description="状态",
     *         required=true,
     *         explode=true,
     *         @OA\Schema(
     *             type="array",
     *             default="available",
     *             @OA\Items(
     *                 type="string",
     *                 enum = {"available", "pending", "sold"},
     *             )
     *         )
     *     ),
Copy after login

Body is submitted in Json mode

     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(
     *                     property="id",
     *                     type="string"
     *                 ),
     *                 @OA\Property(
     *                     property="name",
     *                     type="string"
     *                 ),
     *                 example={"id": 10, "name": "Jessica Smith"}
     *             )
     *         )
     *     ),
Copy after login

Learn more about the use of Laravel Swagger

Use structure Schema as request parameter

     *     @OA\RequestBody(
     *         description="order placed for purchasing th pet",
     *         required=true,
     *         @OA\JsonContent(ref="#/components/schemas/UserModel")
     *     ),
Copy after login

Usage of Schema

/**
 * @OA\Schema(
 *      schema="UserModel",
 *      required={"username", "age"},
 *      @OA\Property(
 *          property="username",
 *          format="string",
 *          description="用户名称",
 *          example="小廖",
 *      ),
 *      @OA\Property(
 *          property="age",
 *          format="int",
 *          description="年龄",
 *          example=1,
 *          nullable=true,
 *      )
 * )
 */
Copy after login

Enumeration

An enumeration creates a Schema separately

/**
 * @OA\Schema(
 *   schema="product_status",
 *   type="string",
 *   description="The status of a product",
 *   enum={"available", "discontinued"},
 *   default="available"
 * )
 */
Copy after login

Mapped to the model Specific fields

 *      @OA\Property(
 *     property="status",
 *     ref="#/components/schemas/product_status"
 *      ),
Copy after login

So that front-end developers can

Associate the model

It is similar to the enumeration, through a Property association model

 *      @OA\Property(
 *     property="user_detail",
 *     ref="#/components/schemas/UserModel2"
 *      ),
Copy after login

Associate the model and the enumeration For example, the requested parameters and parameters can be automatically generated, and the returned structure
Learn more about the use of Laravel Swagger

is returned to the model structure

     *     @OA\Response(
     *         response=200,
     *         description="successful operation",
     *         @OA\JsonContent(
     *             type="array",
     *             @OA\Items(ref="#/components/schemas/UserModel"),
     *             @OA\Items(ref="#/components/schemas/UserModel2")
     *         )
     *     ),
Copy after login

Just like the day the front-end girl told you, brother, payment status What does 3 stand for? Maybe you can quickly tell it is a certain state, but if I ask you what state 11 is, people will be confused.
Through swagger's Schema, front-end personnel can understand the structural information of the back-end, such as:

Learn more about the use of Laravel Swagger

Everyone, these can be programmed automatically and generated automatically, and the work efficiency is not required Too cool

Multiple merged Schemas

/**
 * @OA\Schema(
 *   schema="UserModel",
 *   allOf={
 *     @OA\Schema(ref="#/components/schemas/UserModel2"),
 *     @OA\Schema(
 *       type="object",
 *       description="Represents an authenticated user",
 *       required={
 *         "email",
 *         "role",
 *       },
 *       additionalProperties=false,
 *       @OA\Property(
 *         property="email",
 *         type="string",
 *         example="user@example.com",
 *         nullable=true,
 *       ),
 *     )
 *   }
 * )
 */
Copy after login

Verification provides two methods, outh2 and apikey, and is written in the global configuration (can also be in any directory)

/**
 * @OA\SecurityScheme(
 *     type="apiKey",
 *     in="query",
 *     securityScheme="api_key",
 *     name="api_key"
 * )
 */
Copy after login

In Add

security={{"api_key": {}}},
Copy after login

to the interface. At this time, a lock-like thing will appear in the swagger Ui.

Learn more about the use of Laravel Swagger

You can enter your own token, and the token will be brought when making a request.

Learn more about the use of Laravel Swagger
It can be combined with Laravel's own token verification. You can refer to the previously written article Laravel guard Chrysanthemum Guardian

For more usage methods, you can view the official website examples: https:/ /github.com/zircote/swagger-php/tree/master/Examples/petstore-3.0

Possible problems

If the online environment cannot be accessed, It may be a problem with your nginx configuration, because laravel-swagger echoes the js output through file_content_get(). Judging from your nginx configuration, if it is a .js or css file, it is a static file, so index.php cannot be reached, and the file_content_get function cannot be executed. You can refer to nginx configuration:

charset utf-8;
client_max_body_size 128M;

location / {
	try_files $uri $uri/ /index.php$is_args$args;
}


location ~ \.php$ {
	include fastcgi_params;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	fastcgi_pass  php74:9000 这个换成你自己的;
	try_files $uri =404;
}
Copy after login

[Related recommendations: laravel video tutorial]

The above is the detailed content of Learn more about the use of Laravel Swagger. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template