Я столкнулся с проблемой в Swagger api?

#swagger #swagger-ui #swagger-codegen #swagger-editor #swagger-node-express

#swagger #swagger-пользовательский интерфейс #swagger-codegen #swagger-editor #swagger-node-express

Вопрос:

Swagger.yml

 swagger: "2.0"
info:
  version: "0.0.1"
  title: Movie DB
# during dev, should point to your local machine
host: localhost:8000
# basePath prefixes all resource paths 
basePath: /
# 
schemes:
  # tip: remove http to make production-grade
  - http
  - https
# format of bodies a client can send (Content-Type)
consumes:
  - application/json
# format of the responses to the client (Accepts)
produces:
  - application/json
paths:
  /movies:
    # binds a127 app logic to a route
    x-swagger-router-controller: movies
    get:
      description: Returns 'Hello' to the caller
      # used as the method name of the controller
      operationId: index
      parameters:
        - name: name
          in: query
          description: The name of the person to whom to say hello
          required: false
          type: string
      responses:
        "200":
          description: Success
          schema:
            # a pointer to a definition
            $ref: "#/definitions/MovieListBody"
        # responses may fall through to errors
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
  /swagger:
    x-swagger-pipe: swagger_raw
# complex objects have schema definitions

    post:
      description: Creates a new movie entry
      operationId: create
      parameters:
        - name: movie
          required: true
          in: body
          description: a new movie details
          schema:
            $ref: "#/definitions/MovieBody"
      responses:
        "200":
          description: a successfully stored movie details
          schema:
            $ref: "#/definitions/MovieBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse" 

definitions:
  MovieListBody:
    required:
      - movies
    properties:
      movies:
        type: array
        items:
          $ref: "#/definitions/Movie"

  Movie:
    required:
      - title
      - gener
      - year
    properties:
      title:
        type: string
      gener:
        type: string
      year:
        type: integer

  MovieBody:
    required:
      - movie
    properties:
      movie:
        $ref: "#/definitions/Movie"

  ErrorResponse:
    required:
      - message
    properties:
      message:
        type: string
  

Я получаю эту ошибку:

Маршрут определен в спецификации Swagger (/ movies), но нет определенной операции post

Я новичок в этой концепции Swagger API. Я попробовал crud-операцию в Swagger API. get Метод работает нормально, но я пытался post показать проблему такого типа. Я пробовал шаг за шагом просматривать видеоролики Swagger API. Я попробовал функцию get, данные успешно получены в db. но я попытался отправить данные в mongodb с помощью Swagger API, он выдает ошибку такого типа….

Как это исправить? Кто-нибудь может предложить какое-либо решение?

Ответ №1:

Вам не нужен /swagger узел, просто post узел на том же уровне, что и get узел под /movies path. POST и GET — это операции, которые могут быть выполнены на конечной точке ‘movies’.

В настоящее время ваш swagger поддерживает GET /movies/ и POST /swagger/ , поскольку у вас есть путь под названием ‘swagger’.

Структура должна стать:

 paths:
  /movies:
    get:
      # All the get properties
    post:
      # All the post properties
definitions:
  # All the definitions you need
  

И вот обновленная копия вашего swagger:

 swagger: "2.0"
info:
  version: "0.0.1"
  title: Movie DB
# during dev, should point to your local machine
host: localhost:8000
# basePath prefixes all resource paths 
basePath: /
# 
schemes:
  # tip: remove http to make production-grade
  - http
  - https
# format of bodies a client can send (Content-Type)
consumes:
  - application/json
# format of the responses to the client (Accepts)
produces:
  - application/json
paths:
  /movies:
    # binds a127 app logic to a route
    x-swagger-router-controller: movies
    get:
      description: Returns 'Hello' to the caller
      # used as the method name of the controller
      operationId: index
      parameters:
        - name: name
          in: query
          description: The name of the person to whom to say hello
          required: false
          type: string
      responses:
        "200":
          description: Success
          schema:
            # a pointer to a definition
            $ref: "#/definitions/MovieListBody"
        # responses may fall through to errors
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse"
    post:
      description: Creates a new movie entry
      operationId: create
      parameters:
        - name: movie
          required: true
          in: body
          description: a new movie details
          schema:
            $ref: "#/definitions/MovieBody"
      responses:
        "200":
          description: a successfully stored movie details
          schema:
            $ref: "#/definitions/MovieBody"
        default:
          description: Error
          schema:
            $ref: "#/definitions/ErrorResponse" 
definitions:
  MovieListBody:
    required:
      - movies
    properties:
      movies:
        type: array
        items:
          $ref: "#/definitions/Movie"

  Movie:
    required:
      - title
      - gener
      - year
    properties:
      title:
        type: string
      gener:
        type: string
      year:
        type: integer

  MovieBody:
    required:
      - movie
    properties:
      movie:
        $ref: "#/definitions/Movie"

  ErrorResponse:
    required:
      - message
    properties:
      message:
        type: string
  

Комментарии:

1. Я обновил ответ с правильной иерархией.

2. Я попробовал эту структуру, но это выдает другое «сообщение» об ошибке: «Проверка запроса не удалась: параметр (фильм) не прошел проверку схемы»,

3. можете дать мне пример кода crud-операции Swagger api или видео … плз

4. Я обновил ответ обновленной версией вашего swagger, которая синтаксически допустима.

5. Я попробовал этот шаблон, но выдал ошибку этого типа Ошибка: проверка ответа не удалась: не удалось проверить схему. как решить эту ошибку. и можете ли вы объяснить, что это за ошибка