Подтвердить что ты не робот

Как импортировать Swagger API в Почтальон?

Недавно мне написали успокоительные API с SpringMvc и swagger-ui (v2). Я заметил функцию импорта в Почтальоне:

enter image description here

Итак, мой вопрос, как создать файл, который нужен Почтальону?

Я попробовал поискать в Google, но в моей ситуации не было ответов.

Кстати, я не знаком с Swagger.

4b9b3361

Ответ 1

Я работаю над PHP и использовал Swagger 2.0 для документирования API. Документ Swagger создается на лету (по крайней мере, это то, что я использую в PHP). Документ создается в формате JSON.

Пример документа

{
    "swagger": "2.0",
    "info": {
    "title": "Company Admin Panel",
        "description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
        "contact": {
        "email": "[email protected]"
        },
        "version": "1.0.0"
    },
    "host": "localhost/cv_admin/api",
    "schemes": [
    "http"
],
    "paths": {
    "/getCustomerByEmail.php": {
        "post": {
            "summary": "List the details of customer by the email.",
                "consumes": [
                "string",
                "application/json",
                "application/x-www-form-urlencoded"
            ],
                "produces": [
                "application/json"
            ],
                "parameters": [
                    {
                        "name": "email",
                        "in": "body",
                        "description": "Customer email to ge the data",
                        "required": true,
                        "schema": {
                        "properties": {
                            "id": {
                                "properties": {
                                    "abc": {
                                        "properties": {
                                            "inner_abc": {
                                                "type": "number",
                                                    "default": 1,
                                                    "example": 123
                                                }
                                            },
                                            "type": "object"
                                        },
                                        "xyz": {
                                        "type": "string",
                                            "default": "xyz default value",
                                            "example": "xyz example value"
                                        }
                                    },
                                    "type": "object"
                                }
                            }
                        }
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "Email required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getCustomerById.php": {
        "get": {
            "summary": "List the details of customer by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Customer ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the customer"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "404": {
                    "description": "Customer does not exist"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        },
        "/getShipmentById.php": {
        "get": {
            "summary": "List the details of shipment by the ID",
                "parameters": [
                    {
                        "name": "id",
                        "in": "query",
                        "description": "Shipment ID to get the data",
                        "required": true,
                        "type": "integer"
                    }
                ],
                "responses": {
                "200": {
                    "description": "Details of the shipment"
                    },
                    "404": {
                    "description": "Shipment does not exist"
                    },
                    "400": {
                    "description": "ID required"
                    },
                    "default": {
                    "description": "an \"unexpected\" error"
                    }
                }
            }
        }
    },
    "definitions": {

    }
}

Это можно импортировать в Postman, как показано ниже.

  • Нажмите кнопку Импорт "в верхнем левом углу пользовательского интерфейса Postman.
  • Вы увидите несколько вариантов импорта документа API. Нажмите " Вставить исходный текст".
  • Вставьте формат JSON в текстовую область и нажмите кнопку импорта.
  • Вы увидите все ваши API как " Postman Collection" и сможете использовать его у почтальона.

Импорт JSON в Postman

Импортированные API

Вы также можете использовать "Импорт из ссылки". Здесь вставьте URL-адрес, который генерирует JSON-формат API-интерфейсов из инструмента Swagger или любого другого документа API.

Это файл генерации моего документа (JSON). Это в PHP. Я не знаю JAVA вместе с Swagger.

<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;

Ответ 2

Принятый ответ правильный, но я перепишу полные шаги для java.

В настоящее время я использую Swagger V2 с Spring Boot 2 и это простой трехэтапный процесс.

Шаг 1: Добавьте необходимые зависимости в файл pom.xml. Вторая зависимость является необязательной, используйте ее, только если вам нужен Swagger UI.

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

Шаг 2: Добавить класс конфигурации

@Configuration
@EnableSwagger2
public class SwaggerConfig {

     public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "[email protected]");
      public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
              DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());

    @Bean
    public Docket api() {
        Set<String> producesAndConsumes = new HashSet<>();
        producesAndConsumes.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(DEFAULT_API_INFO)
                .produces(producesAndConsumes)
                .consumes(producesAndConsumes);

    }
}

Шаг 3: Настройка завершена, и теперь вам нужно документировать API в controllers

    @ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
    @GetMapping(path = "/articles/users/{userId}")
    public List<Article> getArticlesByUser() {
       // Do your code
    }

Использование:

Вы можете получить доступ к своей Документации с http://localhost:8080/v2/api-docs просто скопируйте ее и вставьте в Postman для импорта коллекции.

enter image description here

Необязательный интерфейс Swagger: вы также можете использовать автономный интерфейс без какого-либо другого клиента для отдыха через http://localhost:8080/swagger-ui.html и это довольно хорошо, вы можете разместить свою документацию без каких-либо хлопот.

enter image description here

Ответ 3

  • Нажмите оранжевую кнопку ( "выбрать файлы" )
  • Перейдите к документу Swagger (swagger.yaml)
  • После выбора файла в POSTMAN создается новая коллекция. Он будет содержать папки на основе ваших конечных точек.

Вы также можете получить несколько файлов образцов для разборки в Интернете, чтобы убедиться в этом (если у вас есть ошибки в вашем документе swagger).